Python Regular ExpressionsGet Certified
What Is a Regular Expression?
A regular expression, often shortened to regex, is a compact pattern that describes a set of strings. Instead of searching for one exact word, you describe a shape, such as “five digits in a row” or “letters, then an @ sign, then a domain name”. Python can then find, check, extract, or replace every piece of text that fits the shape.
Regular expressions are used in real programs all the time: checking that a ZIP code or phone number is typed correctly, pulling dates and email addresses out of a long document, cleaning messy spaces, and splitting text on several different separators. In Python they live in the built-in re module, so you only need one import re line to start. The patterns look strange at first, but a small set of building blocks covers most of what you will ever need.
- The re module:
import regives yousearch(),match(),findall(),sub(),split(), and more. - Character classes:
\dis a digit,\wis a letter, digit, or underscore,\sis whitespace, and.is any character except a new line. - Quantifiers:
+means one or more,*means zero or more,?means optional, and{3}means exactly three. - Anchors:
^matches the start of the text,$matches the end, and\bmatches a word boundary. - Groups: parentheses
( )capture part of a match, and(?P<name>...)gives the part a name. - Raw strings: write patterns as
r"..."so Python leaves the backslashes alone.
Searching for a Pattern with re.search()
The function re.search(pattern, text) scans the text from left to right and stops at the first place where the pattern matches. If it finds a match, it returns a match object that stores what was found and where. If nothing matches, it returns None, which is treated as false in an if statement.
The match object has helpful methods: group() returns the matched text, and start() and end() give its position in the original string. Notice that the pattern is written as a raw string with the prefix r. Without it, Python would read \d as an unusual escape sequence, and larger patterns would quickly break.
Try It: Find a Time in a Sentence
Click Test My Code to run the program. Then change the sentence to include a different time and run it again.
None.import re
text = "Our office in Austin opens at 9:30 AM."
match = re.search(r"\d+:\d+", text)
print(match)
print(match.group())
print(match.start(), match.end())
print(re.search(r"Boston", text))import re loads Python’s built-in regular expression module.\d+ means one or more digits, and the colon matches itself. So \d+:\d+ matches digits, a colon, and more digits. search() returns the first match.<re.Match object; span=(30, 34), match='9:30'>. It shows the position and the matched text.group() returns only the text that matched. The output is 9:30.start() and end() give the index where the match begins and where it ends, so the output is 30 34.search() returns None and the output is None.Finding Every Match with findall()
While search() stops at the first match, re.findall(pattern, text) collects every non-overlapping match and returns them as a list of strings. This is the fastest way to pull all the phone numbers, dates, or ZIP codes out of a paragraph. If nothing matches, you simply get an empty list.
Quantifiers let you say how many characters you expect. In \d{3} the number in braces means exactly three digits, and \d{5} means exactly five. The word boundary \b is a zero-width marker that matches the edge of a word, which stops a five-digit pattern from matching the first five digits of a longer number.
Try It: Extract Phone Numbers and ZIP Codes
Click Test My Code. Then add another phone number or ZIP code to the text.
import re
text = "Call Emily at 512-555-0142 or Jackson at 303-555-0188."
phones = re.findall(r"\d{3}-\d{3}-\d{4}", text)
print(phones)
zips = re.findall(r"\b\d{5}\b", "Mail to 78701, 02108, or 98101-1234.")
print(zips)re module is needed for every example in this lesson.\d{3}-\d{3}-\d{4} means three digits, a hyphen, three digits, a hyphen, and four digits. findall() returns every match as a list.['512-555-0142', '303-555-0188'].\b\d{5}\b matches exactly five digits with a word boundary on each side. In 98101-1234 the first five digits qualify because the hyphen is a boundary, but 1234 is too short.['78701', '02108', '98101']. The leading zero of 02108 is kept because the values are strings.Anchors and Quantifiers: Validating Input
Anchors tie a pattern to the edges of the text. The caret ^ means “the match must start here” and the dollar sign $ means “the match must end here”. When you put both around a pattern, the whole string must fit the pattern, which is exactly what you want when you validate a form field.
Quantifiers describe repetition, and a group followed by ? makes that whole group optional. A United States ZIP code is five digits, optionally followed by a hyphen and four more digits. The function re.match() checks for a match only at the very beginning of the string, so together with $ it makes a tidy validator.
Try It: Validate ZIP Codes
Click Test My Code. Then add your own ZIP code to the list to see whether it is valid.
import re
zip_pattern = r"^\d{5}(-\d{4})?$"
for code in ["78701", "98101-1234", "9810", "ABCDE"]:
if re.match(zip_pattern, code):
print(code, "is valid")
else:
print(code, "is not valid")import re makes re.match() available.^ anchors the start and $ anchors the end. \d{5} is five digits, and (-\d{4})? is an optional group made of a hyphen and four digits.code.re.match() returns a match object when the value fits and None when it does not. A match object counts as true in an if statement.78701 is valid and 98101-1234 is valid.re.match() returns None.9810 has only four digits and ABCDE has no digits at all. The outputs are 9810 is not valid and ABCDE is not valid.Groups and Named Groups
Parentheses do two jobs in a regular expression: they group parts of a pattern together, and they capture the text that matched inside them. After a successful match, groups() returns a tuple holding the text of every captured group, in order. You can also ask for a single group by number with group(1).
Numbers are hard to remember in a long pattern, so Python lets you name a group with the syntax (?P<name>...). You then read the value with group("name"). Groups turn a match into structured data, which makes it easy to split a date into a month, a day, and a year without extra string slicing.
Try It: Split a Date and Find a City
Click Test My Code. Then change the date or the city in the sentence.
import re
text = "Born on 07/04/2005 in Philadelphia"
m = re.search(r"(\d{2})/(\d{2})/(\d{4})", text)
print(m.groups())
month, day, year = m.groups()
print("Year:", year, "Month:", month)
named = re.search(r"(?P<city>[A-Z][a-z]+)$", text)
print(named.group("city"))re module provides search().groups() returns a tuple of the captured text. The output is ('07', '04', '2005').Year: 2005 Month: 07. The values are still strings, so the leading zero is kept.(?P<city>...) names the group city. The pattern [A-Z][a-z]+$ matches a capital letter followed by lowercase letters at the very end of the text.group("city") returns the captured text. The output is Philadelphia.Replacing and Splitting Text
The function re.sub(pattern, replacement, text) finds every match and replaces it, returning a new string. It is the tool of choice for cleaning messy input, for example collapsing runs of spaces into a single space. In the replacement text you can refer back to a captured group with \1, \2, and so on.
The function re.split(pattern, text) works like the string method split(), but the separator can be a pattern instead of a fixed character. That lets you break a list on commas, semicolons, or any mixture of both in one step. Neither function changes the original string, because strings in Python are immutable.
Try It: Clean Text and Hide Part of a Phone Number
Click Test My Code. Then try masking a different phone number.
import re
text = "Call me at 212-555-0100 today"
clean = re.sub(r"\s+", " ", text)
print(clean)
masked = re.sub(r"\d{3}-\d{3}-(\d{4})", r"XXX-XXX-\1", clean)
print(masked)
print(re.split(r"[,;]\s*", "Austin, Boston;Denver, Seattle"))re.sub() and re.split() both come from the re module.\s+ matches one or more whitespace characters, and each run of them is replaced by a single space.Call me at 212-555-0100 today.\1 puts that group back, so only the first six digits are hidden.Call me at XXX-XXX-0100 today.[,;]\s* matches a comma or a semicolon followed by any spaces. The output is ['Austin', 'Boston', 'Denver', 'Seattle'].Compiling Patterns and Using Flags
When you use the same pattern many times, you can compile it once with re.compile(). The result is a pattern object that has the same methods as the re module, such as search(), findall(), and finditer(). Compiling makes the code tidier because the pattern has a name and is written in only one place.
Flags change how a pattern behaves. The flag re.IGNORECASE, or re.I for short, makes the pattern ignore the difference between uppercase and lowercase letters. The method finditer() is like findall(), but it gives you a full match object for each result, so you can ask for the position of every match.
Try It: Find Email Addresses with Their Positions
Click Test My Code. Then add another email address with a .com ending to the text.
.com, .edu, or .org, prints each match with its starting position, and counts the matches.import re
pattern = re.compile(r"[\w.]+@[\w-]+\.(?:com|edu|org)", re.IGNORECASE)
text = "Write to emily.clark@austin.edu, SUPPORT@DENVER.ORG, or jim@seattle.net"
for found in pattern.finditer(text):
print(found.group(), "at position", found.start())
print(len(pattern.findall(text)))re.compile() and re.IGNORECASE both come from the re module.(?:...) is a group that does not capture. The flag ignores letter case..net, which the pattern does not allow.finditer() returns one match object for each match found in the text.group() is the matched text and start() is its position. The outputs are emily.clark@austin.edu at position 9 and SUPPORT@DENVER.ORG at position 33.findall() returns a list of two strings, so the output is 2.Greedy vs Non-Greedy Matching and Alternation
By default, quantifiers such as * and + are greedy: they match as much text as possible. When you try to grab the text between two tags, a greedy pattern can run past the first closing tag and swallow everything up to the last one. Adding a question mark, as in .*?, makes the quantifier non-greedy, so it stops at the first possible ending.
The vertical bar | means “or” and is called alternation. The pattern Texas|Ohio|Maine matches any one of the three names. Combining a non-greedy match with a capture group is a very common way to pull out the text between two markers.
Try It: Greedy, Non-Greedy, and Alternation
Click Test My Code. Then compare the first two outputs carefully, and add another state name to the last pattern.
import re
html = "<b>Texas</b> and <b>Ohio</b>"
print(re.findall(r"<b>.*</b>", html))
print(re.findall(r"<b>.*?</b>", html))
print(re.findall(r"<b>(.*?)</b>", html))
print(re.findall(r"Texas|Ohio|Maine", "Ohio, Maine, and Texas"))re module provides findall()..* matches as much as it can, so the match starts at the first <b> and ends at the very last </b>. The output is one long match: ['<b>Texas</b> and <b>Ohio</b>']..*? matches as little as possible, so each match stops at the nearest closing tag. The output is ['<b>Texas</b>', '<b>Ohio</b>'].findall() returns just the text of that group. The output is ['Texas', 'Ohio'].['Ohio', 'Maine', 'Texas'].Using Regular Expressions with input()
Regular expressions pair naturally with user input, because people type data in many slightly different ways. The function input() gives you one line of text, and patterns can then pick out the name, the ZIP code, and the phone number from that line. This is the idea behind many forms and data cleaning scripts.
Remember that search() and match() return None when nothing matches, and calling group() on None causes an AttributeError. A careful program checks the result first, as the conditional expressions in this example do. Doing so keeps the program friendly even when the user forgets part of the information.
Try It: Read a Contact Card
The Program Input box is already filled with one line: Emily Carter 78701 512-555-0142. Click Run Code straight away, then try removing the phone number to see the “not found” message.
import re
line = input("Name, ZIP code, and phone: ")
zip_match = re.search(r"\b\d{5}\b", line)
phone_match = re.search(r"\d{3}-\d{3}-\d{4}", line)
name_match = re.match(r"[A-Za-z]+ [A-Za-z]+", line)
print("Name:", name_match.group() if name_match else "not found")
print("ZIP:", zip_match.group() if zip_match else "not found")
print("Phone:", phone_match.group() if phone_match else "not found")re module is needed for the three searches below.input() reads the first line of the Program Input box as one string, such as "Emily Carter 78701 512-555-0142".\b\d{5}\b looks for exactly five digits as a separate word. The result is a match object or None.re.match() checks only the start of the line. [A-Za-z]+ [A-Za-z]+ matches a first name, a space, and a last name.group() only when the match exists. The output is Name: Emily Carter.ZIP: 78701. If the ZIP code were missing, the output would be ZIP: not found.Phone: 512-555-0142.Tip: Build a pattern in small pieces and test each piece on its own. A pattern that you can read piece by piece is much easier to fix than one long string of symbols.
Common Mistakes with Regular Expressions
Regular expressions are powerful, but their short symbols make small mistakes easy to miss and hard to see. Most problems come from forgetting the raw string prefix, mixing up the search functions, or writing a pattern that matches more or less than intended. When a pattern misbehaves, test it on a very short string first and add one piece at a time.
- Forgetting the raw string:
"\d+"may work by accident, but"\b"withoutrmeans a backspace character. Always writer"\b". - Using match() when you mean search():
re.match()only looks at the start of the string, sore.match(r"\d+", "Room 12")returnsNone. - Calling group() on None: if nothing matched,
search()returnsNoneand.group()raises anAttributeError. Check the result first. - Forgetting to escape special characters: a dot means “any character”. To match a real period, write
\., and do the same for(,),+,?, and$. - Greedy surprises:
.*can match far more than you expect. Use.*?when you want the shortest match. - Missing anchors in validation: without
^and$, the pattern\d{5}acceptsabc12345xyz. - Expecting findall() to return whole matches with groups: when the pattern has groups,
findall()returns the groups, not the full matched text. - Writing patterns that are too clever: a very long pattern is hard to read and hard to debug. Split the job into several simple steps.
Good Habits for Writing Regular Expressions
Good regular expressions are short, tested, and explained. A little care when you write them saves a lot of time when you or someone else has to read them again months later. These habits will help you use regular expressions with confidence and avoid the most common traps.
- Always write patterns as raw strings, such as
r"\d{3}-\d{4}". - Start with the simplest pattern that could work, test it on sample text, and then make it more precise.
- Use
re.compile()and a descriptive variable name when you reuse a pattern, such aszip_pattern. - Use named groups when a pattern has more than two or three groups, so the code explains itself.
- Use
^and$for validation, and\bwhen you search for whole words or numbers. - For simple jobs, prefer string methods such as
startswith(),in, andreplace(). They are easier to read than a pattern. - Add a comment above a complicated pattern that says in plain English what it is meant to match.
Key Takeaways
Regular expressions let you describe text patterns once and apply them to any string. With only a handful of building blocks, you can search, validate, extract, clean, and split text far faster than with manual loops. Review the points below before you move on to object-oriented programming.
- Use
import reand write patterns as raw strings. search()finds the first match anywhere,match()checks the start, andfindall()returns every match.- Character classes (
\d,\w,\s), quantifiers (+,*,?,{n}), and anchors (^,$,\b) are the core building blocks. - Parentheses capture parts of a match, and
(?P<name>...)gives a group a name. sub()replaces matches andsplit()breaks text on a pattern.re.compile()and flags such asre.IGNORECASEmake repeated patterns cleaner.- Greedy quantifiers take as much as possible, and adding
?makes them non-greedy. - Always check for
Nonebefore callinggroup().
Frequently Asked Questions
Regular expressions raise a lot of questions for new programmers, especially about which function to choose and why a pattern behaves in an unexpected way. The answers below give the short version of the rules you practiced in the examples. Open a question to read the answer, and run the matching example again to see it in action.
What is a regular expression in Python?
A regular expression is a pattern that describes a set of strings. In Python you use the built-in re module to search for the pattern, check whether text fits it, extract the matching pieces, or replace them. For example, \d{5} matches five digits in a row.
What is the difference between re.search(), re.match(), and re.fullmatch()?
re.search() looks for the pattern anywhere in the string. re.match() requires the pattern to match at the start of the string. re.fullmatch() requires the entire string to match the pattern, which makes it a strict choice for validation.
Why should I use raw strings for regular expression patterns?
A raw string, written with the prefix r, tells Python not to treat backslashes as escape sequences. Regular expressions use many backslashes, such as \d and \b. Without a raw string, a pattern like “\b” means a backspace character instead of a word boundary.
What is the difference between greedy and non-greedy matching?
Greedy quantifiers such as .* match as much text as possible. Non-greedy quantifiers, written with a question mark as in .*?, match as little as possible. Use the non-greedy form when you want the text between the first pair of markers.
How do I match a special character such as a period or a parenthesis?
Put a backslash in front of it. A plain dot matches any character, but \. matches a real period. The same applies to ( ) [ ] { } + * ? $ ^ and |. You can also use re.escape() to escape a whole string automatically.
Why does re.findall() return tuples or only part of the match?
When the pattern contains capture groups, findall() returns the text of the groups instead of the whole match. With one group you get a list of strings, and with several groups you get a list of tuples. Use a non-capturing group such as (?:…) or finditer() to get the whole match.
How do I make a regular expression ignore upper and lower case?
Pass the flag re.IGNORECASE, or re.I, to the function or to re.compile(). For example, re.search(r”texas”, text, re.IGNORECASE) matches Texas, TEXAS, and texas. You can combine several flags with the vertical bar.
When should I not use a regular expression?
Avoid a regular expression when a simple string method does the job, such as startswith(), in, or replace(). Also avoid using it to parse complex nested formats like HTML or JSON, where a dedicated parser is safer. A very long pattern that nobody can read is also a sign to simplify.