How to Set up a Negative Look-behind Regular Expression in Python



Python


In this article, we show how to set up a negative look-behind regular expression in Python.

A negative look-behind regular expression is a regular expression that looks behind elements that you want to match at some negative position behind what you reference.

Let's say we have the following string, string1= "5 undershirts cost $20, 8 boxers cost $25, 2 pairs of jeans cost $40"

If we take the dollar sign ($) and look behind for the number that appears before each $dollar sign, we are looking behind the $ at some negative index before the dollar sign ($).

We can then tally up how many units of clothing a person is buying and get the total amount of units for the purchase.

This is a negative look-behind regular expression.

Again, a negative look-behind regular expression looks behind some part of a string for a given pattern, in this case a digit before each dollar sign ($) in the string.

So let's actually go through a real example in code, so that you can see how it would work.

This is shown in the code below.



So let's now go over this code.

re is the module in Python that allows us to use regular expressions. So we first have to import re in our code, in order to use regular expressions.

After this, we have a variable, string1, which is the quantity of a couple of items and the cost of those items.

We create a regex variable next, which is set equal to, re.compile(r"(?(?We then have our regex variable, which is set equal to, re.compile(r"(?<=\d\))\w+")

?<= means that this is a look behind regular expression.

re.compile(r"(?It looks behind for digits before each dollar sign($) and returns these digits.

We then have the variable, matches, which stores all the matches for this negative look-behind regular expression.

We then have a for loop that loops through each item that was a match. We return this.

After this, we have a variable, total, which functions to keep a total of the quantity of items in the string. Originally, total is initialized to 0.

We then have a for loop that adds i to total for each match.

At the end, we print out the total, which is the total quantity of items in the string.

So this is a good, practical example of a negative look-behind regular expression in Python and how to code it.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...