Regex Reference
Regular expression pattern mappings on text streams.
Compare pattern matching at the start of a string vs anywhere in the string.
Used In: Header matching, pattern verification.
re.search(pat, s) / re.match(pat, s)import re
s = 'ID: 100'
print(bool(re.match('100', s)), bool(re.search('100', s)))False TrueTime Complexity: O(N)
Related Methods: re.search()
Find all substring matches for a regex pattern.
Used In: Parsing logs, extracting numbers or email IDs.
re.findall(pattern, string)import re
print(re.findall(r'\d+', 'User 123 has id 456'))['123', '456']Time Complexity: O(N) where N is characters count
Common Mistakes: Not escaping backslashes inside regex patterns (use raw string r'...' to prevent issues).
Related Methods: re.finditer()
Find all matching occurrences as an iterator of match objects.
Used In: Streaming log analysis.
re.finditer(pattern, string)import re
matches = re.finditer(r'\d+', 'id 10, id 20')
print([m.group() for m in matches])['10', '20']Time Complexity: O(N)
Related Methods: re.findall()
Substitute occurrences of a pattern with a replacement string.
Used In: Normalizing dirty text fields, removing illegal filename characters.
re.sub(pattern, repl, string)import re
print(re.sub(r'\s+', '_', 'a b c'))'a_b_c'Time Complexity: O(N)
Related Methods: str.replace()
Compile a regular expression pattern into a reusable RegexObject.
Used In: High-throughput log analysis loops.
re.compile(pattern)import re
pat = re.compile(r'\d+')
print(pat.findall('10 records, 20 columns'))['10', '20']Time Complexity: O(1) after compilation
Extract specific parts of a match using parentheses ().
Used In: Parsing structured key-value codes from strings.
match.groups() / match.group(i)import re
m = re.search(r'(\d+)-(\w+)', '123-OOM')
print(m.groups())('123', 'OOM')Time Complexity: O(N)
Related Methods: Named Groups
Access captured sub-expression matches using readable dictionary keys.
Used In: Parsing structured log lines into dictionary inputs.
match.groupdict() / (?P<name>pattern)import re
m = re.search(r'(?P<id>\d+)-(?P<tag>\w+)', '123-OOM')
print(m.groupdict()){'id': '123', 'tag': 'OOM'}Time Complexity: O(N)
Related Methods: Capturing Groups
List standard regex patterns for dates, emails, IPs, and phone numbers.
Used In: Data validation, scraping log files.
re.findall(pattern, text)import re
ip_pat = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
print(re.findall(ip_pat, 'IP: 192.168.1.1'))['192.168.1.1']Time Complexity: O(N)