Skip to the solution
MediumBackend11 min read

How do you use regular expressions in Python?

325 views

The problem

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; match anchors at the start only, search scans anywhere, fullmatch must cover the whole string; all return a Match object or None
  • Groups: numbered ( ), named (?P<name>...), non-capturing (?:...); findall returns strings, a list of one group, or tuples depending on how many groups there are, while finditer yields Match objects lazily
  • re.sub with backreferences (\1, \g<name>) or a function, re.split (a capturing group keeps separators), and flags such as IGNORECASE, MULTILINE, DOTALL, VERBOSE, ASCII
  • Greedy vs lazy quantifiers (.+ vs .+?), lookahead and lookbehind, re.escape for user input, and that str patterns are Unicode-aware (\d matches Arabic-Indic digits)
  • CPython details: re.compile returns a Pattern, and module-level calls are cached (512 entries on 3.11); the engine backtracks, so nested quantifiers like (a+)+b can take exponential time; 3.11 added atomic groups and possessive quantifiers
  • Know when not to use a regex: str methods 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.

  • regex
  • re

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 14 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonmatch, search, groups, findall, sub, split, greedy vs lazy and flags
PythonCompiled patterns, lookarounds, Unicode, escaping, atomic groups and classic bugs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 99 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do ThreadPoolExecutor and ProcessPoolExecutor work?

Continue