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

