re.search, re.match, re.fullmatch
re.search(pattern, string, flags=0)
re.match(pattern, string, flags=0)
re.fullmatch(pattern, string, flags=0)Scan a string for a pattern, or require the match to start at the beginning, or to cover the whole string.
Returns: A match object, or None. Calling group() on None raises AttributeError, so check the result first.
- re.match(r"\d+", "port 8080") is None because the string does not start with a digit.
- re.compile(pattern, flags) is useful when the same pattern is applied many times. The resulting Pattern object has search, match, and fullmatch methods.
import re
matched = re.search(r"\d+", "port 8080")
print(matched.group() if matched else None)
print(re.match(r"\d+", "port 8080"))
full = re.fullmatch(r"\d+", "8080")
print(full.group() if full else None)Expected output
8080
None
8080