Choose search, match or fullmatch
Core idea
The re module matches text against patterns. search scans for a match anywhere; match starts at the beginning; fullmatch requires the entire string. A successful call returns a Match object, otherwise None. Raw literals r"..." keep backslashes for the regex engine.
import res = "box OK"print(re.search("OK", s).group())print(re.match("OK", s) is None)print(re.fullmatch("OK", s) is None)group() returns the matched text, but only call it after checking that a match exists.
Compile a reusable pattern
import rep = re.compile("READY")print(p.fullmatch("READY") is not None)print(p.fullmatch("READY NOW") is None)A compiled pattern supports the same matching operations.
Common mistake
match is not whole-string validation. If a pattern must describe the entire input, use fullmatch and separately validate domain rules.
Practice
Try search, match and fullmatch with pattern "OK" against "OK", "OK!" and "status OK".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Matching modes
Check your understanding of pattern matching basics.
What is printed?
import reprint(bool(re.search("A","BA")), bool(re.match("A","BA")))What is printed?
import reprint(re.fullmatch("OK","OK!") is None)What does a failed search return?
Which method validates the entire pattern-shaped input?