189. Advanced Regular Expressions with re

1. Positive Lookahead

import re

# Match 'Python' only if followed by 'Rocks'
pattern = r"Python(?= Rocks)"
text = "Python Rocks is amazing!"
matches = re.findall(pattern, text)
print(matches)  # Output: ['Python']

2. Negative Lookahead

import re

# Match 'Python' only if not followed by 'Rocks'
pattern = r"Python(?! Rocks)"
text = "Python is fun, but Python Rocks too!"
matches = re.findall(pattern, text)
print(matches)  # Output: ['Python']

3. Positive Lookbehind

import re

# Match 'Rocks' only if preceded by 'Python'
pattern = r"(?<=Python )Rocks"
text = "Python Rocks is amazing!"
matches = re.findall(pattern, text)
print(matches)  # Output: ['Rocks']

4. Negative Lookbehind


5. Named Groups


6. Flags: Ignore Case


7. Flags: Multiline Mode


8. Non-Capturing Groups


9. Match with Unicode Characters


10. Combining Multiple Flags


Last updated