Master Python’s re Module: Essential Regex Functions and Patterns
This guide introduces Python’s re module, explaining key functions like search, match, and sub, common regex symbols, quantifiers, character classes, grouping, and how to extract data using findall and groups, all illustrated with clear examples and diagrams.
re module
The Python re module provides regular‑expression operations for pattern matching and text manipulation.
re.search
Typical usage: match = re.search(pat, str). Since a match may not be found, it is common to wrap re.search() in an if statement.
re.match
re.matchis similar to re.search but attempts to match only at the beginning of the string.
Common Regex Characters
a, X, 9 match themselves; meta‑characters such as . ^ $ * + ? { } [ ] \ | ( ) have special meanings.
. matches any character except a newline.
\w matches word characters [a‑zA‑Z0‑9_].
\W matches non‑word characters.
\b matches a word boundary.
\s matches a whitespace character (space, newline, tab, return, form‑feed).
\S matches a non‑whitespace character.
\t, \n, \r match tab, newline, and carriage return respectively.
\d matches a digit [0‑9].
^ matches the start of a string.
$ matches the end of a string.
Quantifiers
‘+’ means one or more times, ‘*’ means zero or more times, ‘?’ means zero or one time.
Square Brackets []
Square brackets define a set of characters, acting like an OR: [abc] matches ‘a’, ‘b’ or ‘c’.
Group Extraction with Parentheses ()
Parentheses create capture groups. For example, the pattern r'([\w.-]+)@([\w.-]+)' captures the username and hostname of an email address; after a successful match you can retrieve them with match.group(1) and match.group(2) while match.group() returns the entire match.
findall and Groups
When () is combined with findall(), the function returns a list of tuples containing the captured groups.
re.sub
re.sub(pat, replacement, str)searches str for substrings matching pat and replaces them with replacement. The replacement string can include backreferences like \1 or \2 to insert captured groups, enabling selective substitution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
