Advanced Regular Expressions

With a Positive Lookahead, you can peek ahead at the next character, ensuring you don't get stuck in an infinite loop!

Example Time! Regular Expressions Are Like Magic!

      
        import re

        # Define the pattern
        pattern = re.compile(r'\d{3}\.\d{3}')

        # Match the first occurrence
        match = re.search(pattern, 'The answer is 42.\nIt has 123.456 digits')

        # Print the result
        print(match.group())
      
    

But Wait, There's More! The Power of Lookahead

With the Positive Lookahead, you can also avoid matching unnecessary characters, like this:

      
        import re

        # Define the pattern
        pattern = re.compile(r'\b\w+\b')

        # Match the first word
        match = re.search(pattern, 'Hello world')

        # Print the result
        print(match.group())
      
    

And for the Love of All That Is Holy... The Dark Side of Lookahead

Be careful, for the Positive Lookahead can also lead to unexpected results, like this:

      
        import re

        # Define the pattern
        pattern = re.compile(r'(\w+)(\w+)(\w+)

        # Match the first three characters
        match = re.search(pattern, 'Hello world')

        # Print the result
        print(match.group())
      
    

And that's not all! The Regex Wizard Has More!

Want to see more examples? Visit our Example Page for more code examples!