Interview Questions: Regular Expressions
Regex questions in interviews test two different things at once: whether the exact pattern syntax is fluent (character classes, quantifiers, anchors, groups), and whether the underlying model of how matching actually works is solid (greedy vs. non-greedy, why raw strings matter, what a failed match returns, when to reach for compile()). This set covers match()/search()/fullmatch(), findall()/finditer(), the pattern vocabulary, groups and named groups, re.sub()/re.split(), re.compile(), the greedy-matching and raw-string gotchas, flags, and one question interviewers love: why "just write a regex for a valid email" is a trap question with no single right answer.
1 What's the actual difference between re.match(), re.search(), and re.fullmatch()?
All three test the same kind of thing — does a pattern match against a string — but they differ in where the match is allowed to happen. re.match(pattern, text) only succeeds if the pattern matches starting at position 0; if the pattern would match later in the string but not at the very start, match() still returns None. re.search(pattern, text) scans the entire string and succeeds on the first match found anywhere, which is why it's almost always the right default when a pattern could be located anywhere in real, messy text. re.fullmatch(pattern, text) is the strictest of the three: it only succeeds if the pattern matches the entire string from the first character to the last, with nothing left over on either side — exactly the right tool for form validation, where the question is "is this whole input a valid email/username/ZIP code?" rather than "does something like that appear somewhere in it?"
Treating match() and search() as interchangeable, or reaching for search() when validating a whole input field (which can incorrectly pass input that merely contains a valid-looking substring rather than being entirely valid).
"Would re.search(r'\d{5}', 'abc123456') succeed, even though the string is not a valid 5-digit ZIP code on its own?" (Yes — search() only needs to find a matching 5-digit run somewhere in the string, so it succeeds even on messy, non-ZIP-shaped input; re.fullmatch(r'\d{5}', 'abc123456') would correctly return None.)
2 What does a failed regex match actually return, and what should calling code check for?
re.match(), re.search(), and re.fullmatch() all return None on failure and a Match object on success — never an exception, and never an empty string. Since a Match object is truthy and None is falsy, the idiomatic check is a plain if re.search(pattern, text): rather than comparing against None explicitly or wrapping the call in a try/except. This is worth being precise about in an interview, since a common mistake is assuming a failed match raises an exception (it never does) or returns something like an empty Match object (there's no such thing — it's None or nothing).
Wrapping a regex match in try/except to "catch" a failed match, or checking if match != "" instead of the correct truthy/None check.
"Does re.search(r'\d+', 'no digits here') raise an exception?" (No — it simply returns None; regex functions never raise on a failed match, only on a malformed pattern string itself, which is a separate, much rarer failure mode.)
3 What's the difference between re.findall() and re.finditer(), and when would you reach for one over the other?
Both scan the whole string and return every match, not just the first — the difference is in what shape the results come back as. re.findall() returns a plain list of strings (or tuples, if the pattern has multiple groups), which is exactly right when only the matched text itself is needed. re.finditer() returns an iterator of Match objects instead — each one carries the match's .start()/.end() position in the original string, plus access to any groups via .group()/.groupdict(), information findall() throws away. The rule of thumb: reach for findall() for a quick "just give me the matched text" job, and finditer() the moment position or per-match group data matters, since findall() genuinely cannot provide either.
Not knowing that findall() discards position information entirely, or assuming finditer() is just a slower version of the same thing with no functional difference.
"If a pattern like r'\[(?P<level>\w+)\]' needs both the matched text and where each match starts in the original string, which function should be used?" (re.finditer() — findall() would return only the matched text or captured groups, with no way to recover each match's position afterward.)
4 What's the difference between a character class, a quantifier, and an anchor?
These are three genuinely different kinds of pattern pieces, and confusing them is a common early mistake. A character class ([aeiou], \d, \w, \s) matches exactly one character, chosen from some set. A quantifier (*, +, ?, {m,n}) doesn't match a character at all on its own — it modifies whatever comes immediately before it, saying how many times that piece is allowed to repeat. An anchor (^, $, \b) matches a position in the string, not a character — it never consumes any text itself, it just asserts something about where the surrounding pattern is located (start of string, end of string, a word boundary). A full pattern like r"^\d{3}-\d{4}$" combines all three: ^/$ are anchors, \d is a character class, and {3}/{4} are quantifiers.
Calling ^ or $ a "character that gets matched," or not being able to explain that a quantifier has no meaning by itself — it always modifies the token directly before it.
"Does the pattern r'^$' ever match a character?" (No — both ^ and $ are pure position anchors with zero width, so r'^$' only matches the empty string: the position where the string starts is immediately followed by the position where it ends, with nothing in between.)
5 Why does an unescaped . in a regex pattern behave unexpectedly to beginners?
Because . on its own doesn't mean "a literal period" at all — it means "any single character except a newline." A pattern like r"c.t" matches "cat", "cot", "c9t", and even "c.t" itself, since an actual period is just one of the many characters . is willing to match in that position. To match a literal period specifically, it has to be escaped with a backslash: r"c\.t" matches only "c.t". This trips people up constantly when writing patterns for things like decimal numbers, file extensions, or domain names, where the period is meant literally but gets typed unescaped — the pattern still "works" in the sense that it doesn't error, it just silently matches more than intended.
Believing . matches a literal dot by default, or not knowing that this mistake fails silently (over-matching) rather than raising any kind of error.
"Would the unescaped pattern r'3.14' match the string '3x14'?" (Yes — the unescaped . matches any character in that position, including x, so r'3.14' incorrectly matches '3x14' as well as the intended '3.14'; the fix is r'3\.14'.)
6 What's the difference between a numbered group and a named group, and why would you prefer one over the other?
Both are created by wrapping part of a pattern in parentheses, and both let that piece be retrieved separately from the rest of the match afterward — the difference is purely in how that piece gets referenced later. A plain group, (...), is retrieved by position: match.group(1), match.group(2), numbered left to right in the order the parentheses appear (group 0 is always the entire match). A named group, (?P<name>...), matches exactly the same text but is retrieved by a meaningful string name instead: match.group("year"). Named groups are almost always the better choice once a pattern has more than one or two groups, since group(1) says nothing about what that piece actually represents, and inserting a new group earlier in the pattern later silently shifts every numbered reference after it — a bug that's easy to introduce and easy to miss. Named groups don't have that fragility, and match.groupdict() conveniently returns every named group at once as a ready-to-use dictionary.
Not knowing that inserting a new group earlier in a pattern re-numbers every group after it, or being unable to name the syntax for a named group.
Follow-up"If a working pattern with three numbered groups gets a brand-new fourth group added at the very front, does match.group(1) still refer to the same piece it did before?" (No — the new group at the front becomes group 1, and everything that used to be groups 1-3 shifts to groups 2-4, silently breaking any code that referenced them by number; named groups avoid this entirely since they're referenced by name regardless of position.)
7 What happens when calling .group() for a group that's part of an optional piece of the pattern that didn't actually participate in the match?
It returns None, not an empty string. If part of a pattern is optional (via ?, or one side of an alternation with |) and that specific piece never matched anything on a given input, the corresponding group is considered to have "not participated" in the match at all — and Python represents that specifically as None, distinct from the group having matched an empty string. This distinction matters in practice: code that calls a string method on a group's result (like .upper() or .strip()) without first checking for None will crash with an AttributeError the moment that optional group doesn't participate, even though the overall match succeeded.
Assuming a non-participating group returns an empty string, or not anticipating that calling a method on it directly can crash even when the overall Match object is not None.
"Given match = re.match(r'(\d+)(x)?', '42'), what does match.group(2) return?" (None — the optional (x)? group never matched anything against '42', so it's reported as not having participated, rather than as an empty string.)
8 How is re.sub() different from str.replace(), and what's a real production use case where that difference matters?
str.replace(old, new) only replaces one exact, fixed string — it has no concept of a pattern at all. re.sub(pattern, replacement, text) replaces every match of an entire pattern, which can describe a whole category of text rather than one fixed value. The production use case that comes up constantly: masking sensitive data before logging or displaying it, e.g. replacing every credit-card-number-shaped or phone-number-shaped substring in a block of text with "XXXX-XXXX-XXXX-XXXX" in a single re.sub() call — something str.replace() simply cannot do, since it would need to already know every specific number appearing in the text ahead of time. re.sub() also supports referencing captured groups in the replacement string (\1, \2, ...), which lets it rearrange matched text rather than only deleting or masking it.
Describing re.sub() as "just a fancier replace()" without being able to name a concrete case where a fixed-string replace genuinely cannot do the job.
"Could text.replace(phone_number, 'XXX-XXXX') mask every phone number in a block of text containing several different numbers, in one call?" (No — str.replace() only replaces one specific string value per call, so masking several distinct phone numbers would require one call per distinct number, or knowing every number in advance; re.sub(r'\d{3}-\d{4}', 'XXX-XXXX', text) masks all of them in a single call regardless of what the actual digits are.)
9 Why compile a pattern with re.compile() instead of just calling re.search() with a raw pattern string every time?
re.compile(pattern) processes a pattern string once into a reusable compiled pattern object, which then exposes its own .match()/.search()/.findall() methods without needing the pattern string passed in again on every call. The practical benefit shows up specifically when the same pattern gets applied repeatedly — scanning every line of a large log file for the same timestamp shape, for instance — where compiling once outside the loop and reusing the compiled object inside it avoids re-parsing the same pattern string on every single iteration. It's worth being fair about the tradeoff in an interview, though: Python's re module already keeps a small internal cache of recently used pattern strings, so the raw performance difference for a single reused pattern is often smaller than people assume. The clearer, more defensible benefit is readability and intent — a named, compiled pattern object makes it visually obvious that a particular pattern is meant to be reused, rather than being re-typed as a string literal at every call site.
Claiming re.compile() is strictly necessary for reused patterns to work correctly at all (it isn't — correctness is identical either way, only the workflow and clarity differ), or not knowing about the module's internal pattern cache.
"Is calling re.search(pattern, text) with the exact same pattern string 10,000 times in a loop functionally incorrect compared to compiling it first?" (No — it's still correct, and Python's internal cache reduces the practical performance gap; compiling first is mainly a readability and intent-signaling improvement, not a correctness requirement.)
10 What's the difference between a greedy and a non-greedy quantifier? Give a concrete example where the difference produces a different match.
Every quantifier (*, +, {m,n}) is greedy by default: it tries to consume as much text as possible while still letting the rest of the pattern succeed. Adding a ? immediately after a quantifier (*?, +?) makes it non-greedy (or "lazy") instead: it consumes as little text as possible. The classic example is matching HTML-like tags in "<b>bold</b> and <i>italic</i>": the greedy pattern r"<.*>" stretches from the very first < all the way to the very last > in the string, swallowing everything in between as one giant match, since greedy matching is allowed to keep consuming as long as the pattern can still eventually succeed. The non-greedy version, r"<.*?>", instead stops at the very first > it can find, correctly producing four separate small matches ("<b>", "</b>", "<i>", "</i>") instead of one. Whenever a pattern needs "the shortest thing between two delimiters" rather than "everything from the first delimiter to the last one," non-greedy is the fix.
Not being able to produce a concrete example where greedy vs. non-greedy actually changes the result, or thinking non-greedy quantifiers only apply to .* specifically rather than any quantifier.
"Against 'aaa', does the greedy pattern r'a+' and the non-greedy pattern r'a+?' return the same single match from re.match()?" (No — r'a+' greedily matches all three as, 'aaa', while r'a+?' matches the shortest string that still satisfies "one or more," which is just 'a'.)
11 Why does forgetting the r prefix on a regex pattern string cause bugs, and why are those bugs specifically hard to spot?
Because Python processes backslash escape sequences in an ordinary string before the re module ever sees the pattern. A regex pattern uses backslashes constantly — \d, \w, \s, \b — and some of those same two-character sequences already mean something different to Python's own string parser. "\bcat\b" without the r prefix isn't the five characters backslash-b-c-a-t at all: Python's string rules silently convert \b into an actual backspace control character (\x08) first, so re receives a corrupted pattern that can never match anything meaningful. The reason this bug is specifically hard to spot: many other backslash sequences commonly used in regex (like \d or \w) aren't recognized Python escape sequences, so Python leaves them alone and the pattern happens to work fine without r — right up until a sequence like \b, \n, or \t gets added later, at which point it silently breaks with no error raised anywhere. The fix is a blanket rule, not a case-by-case judgment call: write every regex pattern as a raw string, without exception.
Believing a missing r prefix always causes an obvious error (it doesn't — many patterns "work" without it purely by coincidence), or not knowing which specific escape sequences are the dangerous ones.
"Would the pattern "\d+" (without an r prefix) behave any differently from r"\d+"?" (No, in this specific case — \d is not a recognized Python string escape sequence, so Python leaves the backslash alone either way; the danger is patterns using sequences Python does recognize, like \b, \n, or \t, which is exactly why "it happened to work without r once" is not a safe signal that a pattern is fine.)
12 What do the re.IGNORECASE and re.MULTILINE flags actually change?
They're optional extra arguments passed to a re function (or to re.compile()) that change how the entire pattern behaves, and they solve two unrelated, easy-to-forget default behaviors. re.IGNORECASE makes matching case-insensitive — without it, r"python" matches "python" but not "Python" or "PYTHON", since patterns are case-sensitive by default. re.MULTILINE changes what ^ and $ anchor to: by default, they only match the very start and end of the entire string, even if that string spans multiple lines separated by \n; with re.MULTILINE, they instead match the start and end of every individual line within the string. Multiple flags can be combined with the bitwise OR operator, re.IGNORECASE | re.MULTILINE, to apply both at once.
Assuming ^/$ always anchor per-line by default, or not knowing flags can be combined with |.
"Against the string 'start one\nstart two', does re.findall(r'^start', text) find one match or two, without any flag?" (One — without re.MULTILINE, ^ only anchors to the very beginning of the whole string, so it finds the first line's 'start' but not the second line's, even though both lines individually begin with that word.)
13 "Write a regex that validates an email address" is a classic interview prompt. What's the honest answer to give?
A genuinely correct email-validating regex, matching the full RFC 5322 specification, is notoriously long and impractical to hand-write — and the honest, senior answer is to say that up front rather than pretending a short pattern is bulletproof. A practical pattern like r"[\w.+-]+@[\w-]+\.[A-Za-z]{2,}" (used against re.fullmatch()) covers the large majority of real-world addresses correctly and is exactly the kind of pattern actually used in production form validation — but it will reject some technically valid edge cases (quoted local parts, some newer top-level domains) and, in principle, could accept a few unusual strings that aren't real deliverable addresses. The interview-worthy point isn't memorizing a "perfect" pattern; it's knowing that client-side regex validation is a first-pass sanity check, not a guarantee — genuine validation of "does this email actually work" ultimately requires sending a confirmation email and having the recipient click a link, which no regex, however sophisticated, can substitute for.
Presenting any single regex as a fully correct, complete email validator with no caveats, or not knowing that real-world email validation ultimately depends on a confirmation step, not pattern matching alone.
Follow-up"Would a practical email-validation pattern like r'[\w.+-]+@[\w-]+\.[A-Za-z]{2,}' ever be wrong to ship to production?" (No — it's a reasonable, genuinely common first-pass check; the point isn't that it's wrong to use, it's that calling it a complete, airtight validator overstates what any practical regex can guarantee, and a confirmation email remains the actual source of truth.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.