Regular Expressions
A regular expression (regex) is a small pattern for finding or checking text: phone numbers, PIN codes, prices in a message. Python's re module uses them.
Simple searches (does this text contain "sale"?) only need in. But some questions are about patterns: is this a valid 6-digit PIN code? Find every price like "Rs 499" in a message. Extract all email addresses from a page. Regular expressions describe such patterns in a compact language that works in Python, JavaScript, Java, Excel, editors and databases.
Regex looks cryptic at first. Learn the building blocks one at a time, test on small examples, and don't try to validate everything with one giant pattern.
Example
Pattern building blocks
\da digit,\wa letter/digit/_,\sa space,.any character+one or more,*zero or more,?optional,{6}exactly six[A-Z]any capital letter,[^0-9]anything except a digit^start,$end,\ba word edge( )a group you can read back
Checking input
Example
Named groups
Example
Write patterns as raw strings:
r"\d+". Without the r, Python treats backslashes specially. Test tricky patterns on a site like regex101.com.Key points
- re.search, re.findall, re.fullmatch, re.sub are the main functions.
- \d digit, \w word char, + one or more, {n} exactly n.
- Use raw strings r"..." for patterns.
- Named groups (?P<name>...) label parts of a match.
📝 Test yourself
1. What does \d{6} match?
2. Which function checks that the WHOLE text matches?
3. Fill in the prefix for a raw string pattern:
re.findall("\d+", text)
