Skip to main content

Foundations of Regular Expressions

The re Module Core Functions

0:00
LearnStep 1/3

Core Matching Functions

Core Matching Functions

The re module provides several functions to find patterns within strings. Understanding the subtle differences between them is crucial for effective regex usage.

re.search() vs. re.match() vs. re.fullmatch()

These three functions are used to find a single match, but they differ in scope:

  • re.search(pattern, string): Scans through the entire string and returns the first location where the regular expression produces a match.
  • re.match(pattern, string): Checks for a match only at the beginning of the string. If the pattern is found elsewhere, it returns None.
  • re.fullmatch(pattern, string): Requires the pattern to match the entire string exactly.
python

Finding Multiple Matches: re.findall() vs. re.finditer()

When you need to extract all occurrences of a pattern, use these functions:

  • re.findall(pattern, string): Returns all non-overlapping matches as a list of strings. If groups are present, it returns a list of groups.
  • re.finditer(pattern, string): Returns an iterator yielding Match objects. This is more memory efficient for many matches and provides more details (like positions) for each match.
python