liveBook · Manning

Re.search

As explained in Python How-To

re.search is a Python re-module function that searches a string for the first match of a regular-expression pattern and returns a match object or None.

Use re.search when a regular-expression pattern may match anywhere in a string. It scans from the beginning until it finds the first match, returning a Match object or None. section 2.4.4 section 2.4.5

Search a string

import re match = re.search(r"(\w\d)+", "xyza2b1c3dd") print(match) # <re.Match object; span=(3, 9), match='a2b1c3'> if match: print(match.group()) print(match.span()) # a2b1c3 # (3, 9) section 2.4.4

Choose the calling style and follow-up operation according to how the pattern is used:

  • Call re.search(pattern, string) for a one-off search; Python creates the pattern object internally. section 2.4.1
  • Compile a pattern when reusing it: the compiled pattern is cached and avoids recompiling on later searches. section 2.4.1
  • Use match when only the string's beginning is valid, findall for matched values without locations, and finditer for multiple Match objects. section 2.4.4 section 2.4.5
Listing 2.6 Methods of a Match object
print("matched:", match.group())
# output: matched: a2b1c3

print("span:", match.span())
# output: span: (3, 9)

print(f"start: {match.start()} & end: {match.end()}")
# output: start: 3 & end: 9

Inspect a Match object through group(), span(), start(), and end() to determine what matched and where it occurred. section 2.4.4

How Python How-To covers it

How deep it goes
Explains direct and compiled calls, Match objects, positions, conditionals, and differences from match, findall, and finditer.
Examples
Uses digit-word patterns, matched text, spans, and direct calls on strings.
What it assumes
Assumes familiarity with regular-expression patterns and introduces the distinction between searching anywhere and matching at the beginning.
What you can do after
Apply it via Python's re module to locate a match and inspect its text and character positions.
How it connects
Connects regular expressions with Pattern objects, Match objects, caching, match, findall, and finditer.

Also explained in

Compare how 2 books explain re.search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.