With a Positive Lookahead, you can peek ahead at the next character, ensuring you don't get stuck in an infinite loop!
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())
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())
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())
Want to see more examples? Visit our Example Page for more code examples!