How to search text with Regular Expressions?ΒΆ
The builtin module re implements Regular Expression, a powerful syntax for search patterns in text. You need to know some special characters to build your own patterns, although LLMs should be able to assist with that. Regular Expressions are very similar in most programming languages.
Here are a couple of examples in Python:
import re
text = "the quick brown fox jumps over the lazy dog"
# Search for `o` and show adjacent characters:
print(re.findall(r".o.", text))
# Search for three-letter words enclosed by whitespace:
print(re.findall(r"\s(\wo\w)\s*", text))
# Substitute any of `dflj` by a `w`:
print(re.sub(r"[dflj]", "w", text))
# Check if `jumps` or `swims` occurs and return details:
print(re.search(r'jumps|swims', text))
See also
Regex 101 - Shows matched text with explanation.
regexone.com/ - Learn regular expressions by simple, interactive examples. Great place to start.
Regex crossword - Train proper use of single characters, wildcards and square brackets. Easy.
Regex golf - Advanced exercises. Match as many phrases with as few key strokes as possible.