Question presented to candidate:
"Walk me through using regular expressions in Python. What is the difference between re.match, re.search and re.fullmatch, how do groups work, and what mistakes do people make with the re module?"
What a strong answer should cover:
- Write patterns as raw strings (
r"\d+") so backslashes reach the regex engine;matchanchors at the start only,searchscans anywhere,fullmatchmust cover the whole string; all return aMatchobject orNone - Groups: numbered
( ), named(?P<name>...), non-capturing(?:...);findallreturns strings, a list of one group, or tuples depending on how many groups there are, whilefinditeryieldsMatchobjects lazily re.subwith backreferences (\1,\g<name>) or a function,re.split(a capturing group keeps separators), and flags such asIGNORECASE,MULTILINE,DOTALL,VERBOSE,ASCII- Greedy vs lazy quantifiers (
.+vs.+?), lookahead and lookbehind,re.escapefor user input, and thatstrpatterns are Unicode-aware (\dmatches Arabic-Indic digits) - CPython details:
re.compilereturns aPattern, and module-level calls are cached (512 entries on 3.11); the engine backtracks, so nested quantifiers like(a+)+bcan take exponential time; 3.11 added atomic groups and possessive quantifiers - Know when not to use a regex:
strmethods for simple tests, real parsers for HTML, JSON or nested structures
Code / implementation expected: Yes β extract fields from a log line with named groups, plus one substitution and one findall.