How to Set up a Look-ahead Regular Expression in Python


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

A look-ahead regular expression is a regular expression that looks ahead, or in front of elements of a string.

Let's say we have the following string, string1= "Milk butter rice corn onions"

What comes after each element?

A space. A space comes after each element.

Or, rather, the space is after each element.

So looking ahead of each element in the string is a space.

A look-ahead can grab all words separated by a boundary (such as a space, in this example) but it does not include those boundaries in the results returned.

So let's see how we can elements of a string that are all separated by a boundary?

This is shown in the following 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 a couple of elements each separated by a boundary, in this case which is a space.

We then have a regex variable that is set equal to, re.compile(r"\w+(?=\b)")

\w looks for all alphabetical and numerical characters in the elements.

(?=\b) looks ahead of each element to the boundary that separates each element from another.

We then create a variable, matches, which returns all matches of elements separated by a boundary.

We then create a for loop and return all elements of the result.

The look-ahead regular expression again returns all elements separated by a common boundary. In the above example, again, each element is separated by a space. However, if they were separated by any other element, such as a colon or semicolon, the same result would be returned.

This is shown in the code below.

So a look-ahead regular expression can be powerful for looking ahead of each element and returning elements based on a common boundary.

And this how we can set up a look-ahead regular expression in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...