A regular expression is a declarative pattern for finding, extracting, validating, splitting, or replacing text. Instead of manually inspecting characters, describe the pattern and let Python’s regex engine search the input. section 14.0 section 14.5
Build patterns from a small set of useful operations:
- Use character classes such as [aeiou], [A-Za-z0-9], or [^<>] to describe allowed or excluded characters. section 14.1.2 section 18.1.1
- Use re.match() for a match at the beginning, re.search() for a match anywhere, re.split() to divide text, and re.compile() for repeated use. section 14.1.2 section 15.5
- Add quantifiers such as + for one or more characters, and anchors such as $ for the end of a string. section 14.1.2 section 15.1.5
- Wrap parts in parentheses to capture them, then retrieve the captured text with match.group() or match.groups(). section 14.3.2 section 17.1.1
- Remember that * and + are greedy; adding ? makes them non-greedy, while a negated class can express a precise boundary. section 17.1.1 section 17.5
Match initial consonants
Construct a consonant character class, then anchor it to the beginning with re.match(). The + quantifier captures a whole initial cluster, so “chair” produces “ch,” while “apple” produces no match. import re consonants = 'bcdfghjklmnpqrstvwxyz' match = re.match(f'[{consonants}]+', 'chair') print(match.group()) # ch The same pattern supports a rhyming-word program by separating leading consonants from the rest of a word. section 14.1.2
Extract placeholders without overmatching
A greedy pattern such as <.+> consumes from the first opening bracket to the last closing bracket. Use <[^<>]+> instead to stop at a balanced pair and exclude nested brackets. Capture the complete placeholder and its name separately: match = re.search('(<([^<>]+)>)', '<adjective>') print(match.groups()) # ('<adjective>', 'adjective') re.findall() returns every placeholder, allowing a program to prompt for each name before re.sub() replaces the matches. section 17.1.1 section 17.5
>>> re.split("([a-zA-Z](?:[a-zA-Z']*[a-zA-Z])?)", "Don't worry, spiders,")
['', "Don't", ' ', 'worry', ', ', 'spiders', ',']
Inspect a runnable split pattern that preserves words containing apostrophes while separating surrounding punctuation and whitespace. section 16.1.1
Long patterns remain maintainable when adjacent string literals are split across lines and comments document each part. Small functions and tests make regex-based transformations easier to verify and reuse. section 14.3.2 section 14.5


























