Regex search & findall in Python
The core re functions for finding text patterns.
import re
log = "user=ada action=login ip=10.0.0.7"
found = re.search(r"user=(\w+)", log)
user = found.group(1)
numbers = re.findall(r"\d+", log)
starts_ok = re.match(r"user=", log) is not None
words = re.split(r"\s+", log)
has_ip = bool(re.search(r"ip=\d+\.\d+\.\d+\.\d+", log))
How it works
re.searchfinds the first match anywhere.group(1)pulls the captured parenthesized part.findallreturns every match;splitbreaks on one.
Keywords and builtins used here
bool
The run, in numbers
- Lines
- 12
- Characters to type
- 283
- Tokens
- 104
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.
Step 1 of 5 in Regular expressions, step 1 of 41 in Domain tools.