Regex Special Characters

Carson West

Regex Flags

Regex Special Characters

These notes cover special characters used in Regular Expressions within Python. Remember to import the re module before using any regex functions. import re

Regex Metacharacters These are symbols with special meanings in regex.

Regex Quantifiers These characters control how many times a preceding element should appear. (Already mentioned some above, but details here are crucial)

Example:

import re

text = "The quick brown fox jumps over the lazy fox."
pattern = r"fox"  # Matches the literal string "fox"

matches = re.findall(pattern, text)
print(matches)  # Output: ['fox', 'fox']]

pattern = r".ox" # Matches any character followed by "ox"
matches = re.findall(pattern, text)
print(matches) # Output: ['fox', 'fox']]

pattern = r"f.x" # Matches 'f' followed by any character followed by 'x'
matches = re.findall(pattern, text)
print(matches) # Output: ['fox', 'fox']]

pattern = r"The.*fox" # Matches 'The' followed by any characters (except newline) followed by 'fox'
matches = re.findall(pattern, text)
print(matches) # Output: ['The quick brown fox']]

pattern = r"\bf\w+\b" #Matches whole words starting with 'f'
matches = re.findall(pattern,text)
print(matches) # Output: ['fox', 'fox']]

Regex Escape Sequences Details on \d, \w, \s, etc.

Python re Module Functions like re.findall, re.search, re.match, re.sub, etc.