Sobes.tech
Junior — Middle

What are the differences between the functions re.search and re.match from the re module in Python?

sobes.tech AI

Answer from AI

The functions re.match and re.search from the re module in Python differ in where they look for a match:

  • re.match(pattern, string) tries to find a match only at the beginning of the string.
  • re.search(pattern, string) searches for a match anywhere in the string.

Example:

import re

text = "Hello, world!"

# re.match checks only the start of the string
print(re.match("Hello", text))  # Finds a match
print(re.match("world", text))  # None, because 'world' is not at the start

# re.search searches everywhere
print(re.search("world", text))  # Finds a match

Thus, if you need to check whether a string starts with a pattern — use match. If you need to find a pattern anywhere — use search.