Academic Block

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 re gives you search(), match(), findall(), sub(), split(), and more.
  • Character classes: \d is a digit, \w is a letter, digit, or underscore, \s is 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 \b matches 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.

What this code does: It searches a sentence for a time such as 9:30, prints the match object, the matched text, and its position, and then shows that a search with no match returns 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))

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.

What this code does: It extracts every phone number from a sentence, then pulls out the five-digit ZIP codes from an address list and ignores the four extra digits of a ZIP+4 code.
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)

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.

What this code does: It checks four values against a ZIP code pattern that allows five digits with an optional four-digit extension, and prints whether each value 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")

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.

What this code does: It captures the month, day, and year of a date in three groups, unpacks them into variables, and then uses a named group to capture the city at the end of 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"))

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.

What this code does: It collapses extra spaces, hides all but the last four digits of a phone number by reusing a captured group, and splits a list of cities on commas and semicolons.
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"))

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.

What this code does: It compiles a case-insensitive pattern for simple email addresses that end in .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)))

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.

What this code does: It matches bold tags in a short piece of text with a greedy pattern, a non-greedy pattern, and a non-greedy pattern with a group, and it finds any of three state names with alternation.
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"))

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.

What this code does: It reads one line containing a name, a ZIP code, and a phone number, extracts each part with a regular expression, and prints it or reports that it was not found.
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")
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" without r means a backspace character. Always write r"\b".
  • Using match() when you mean search(): re.match() only looks at the start of the string, so re.match(r"\d+", "Room 12") returns None.
  • Calling group() on None: if nothing matched, search() returns None and .group() raises an AttributeError. 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} accepts abc12345xyz.
  • 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 as zip_pattern.
  • Use named groups when a pattern has more than two or three groups, so the code explains itself.
  • Use ^ and $ for validation, and \b when you search for whole words or numbers.
  • For simple jobs, prefer string methods such as startswith(), in, and replace(). 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 re and write patterns as raw strings.
  • search() finds the first match anywhere, match() checks the start, and findall() 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 and split() breaks text on a pattern.
  • re.compile() and flags such as re.IGNORECASE make repeated patterns cleaner.
  • Greedy quantifiers take as much as possible, and adding ? makes them non-greedy.
  • Always check for None before calling group().

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.

Ready for the next step?Start organizing your programs with classes and objects.
Next: OOP Concepts →