Advanced Features
2 min read ·
These features make regular expressions more powerful for searching, modifying, and processing text.
Alternation using |
The pipe symbol is used to match one pattern or another.
Matches:
- cat
- dog
finditer()
Returns an iterator of match objects with detailed information like position.
Note
finditer is useful when you need position of matches along with value.
split()
Splits a string based on a pattern.
Output:
- apple
- banana
- mango
sub()
Replaces matched pattern with new value.
Replace Multiple Values
Pro Tip
Use sub when cleaning or transforming text data.
Combining Features
Caution
Be careful with patterns in sub and split as incorrect pattern can remove important data.
Exercise
- Use | to match multiple words
- Use finditer to print positions
- Split sentence using space and comma
- Replace word using sub