Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingMiddleCommonPractical

What is the difference between `re.match`, `re.search` and `re.fullmatch`, and why should regex patterns usually be compiled?

Answer

`re.match` only checks for a match anchored at the very start of the string, `re.search` scans the whole string for the first location where the pattern matches anywhere, and `re.fullmatch` requires the entire string to match the pattern end to end. `re.compile(pattern)` pre-parses a pattern into a reusable `Pattern` object; its main benefit is explicit reuse and readability — passing a compiled object around and paying the parse cost once at a clear point in the code, plus a small guaranteed lookup saving versus calling `re.match(pattern, ...)` with a raw string each time. The `re` module also internally caches a limited number of recently used compiled patterns, so calling the module-level functions repeatedly with the same pattern string does not necessarily reparse it from scratch every single time — but that cache is an implementation detail with a bounded size, so explicit `compile()` is still the reliable choice inside a loop or hot validation path, or when many distinct patterns are in play.

Strong answer includes

  • match anchors at start, search scans anywhere, fullmatch requires the whole string
  • compile's main benefit is explicit reuse and readability, not just avoiding reparsing
  • re also caches recent patterns internally, but that cache is bounded and implementation-specific

Practical example

Python example
re.match("\\d+", "abc123")

returns None because the digits do not start at position 0, while

Python example
re.search("\\d+", "abc123")

finds `"123"` starting at position 3.

#regex#strings

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules