Python's regular-expression support lives in the re module, part of
the standard library. Import it and you can search text for patterns,
pull out matching pieces, and check that a string has the shape you
expect.
import re
Regex patterns lean heavily on the backslash: \d for a digit, \.
for a literal dot, \s for whitespace. In a normal Python string the
backslash is also an escape character, so "\d" is easy to misread and
"\n" turns into a newline. To keep a pattern exactly as written, use
a raw string by prefixing it with r:
pattern = r"\d+\.\d+"
The r tells Python to leave every backslash alone and hand the raw
text straight to re. Always write regex patterns as raw strings. It
costs nothing and avoids a whole class of confusing bugs.
The quickest way to try a pattern is re.search, which looks for the
pattern anywhere in a string and returns a match object, or None when
there's nothing:
import re
text = "release 1.20 shipped"
match = re.search(r"\d+\.\d+", text)
if match:
print(match.group()) # 1.20
match.group() returns the slice of text the pattern matched. A None
result means no match, which is why the if guard matters before you
call .group().
import re loads the regular-expression module.r"...") keep backslashes intact in patterns.re.search(pattern, text) returns a match object or None.