Module 5 · Beginner · Working with text

Python regular expressions with the re module

Python regular expressions with the re module: search, findall, sub, split, character classes, groups, and patterns for phone numbers and PIN codes.

By theprogrammers team · · 10 min read

You have 2,000 customer messages and need every Indian mobile number in them. Some are written "9876543210", some "98765 43210", some "+91-98765-43210". find() and split() can't handle that, because you're not looking for fixed text. You're looking for a pattern: ten digits, maybe with spaces or a +91 in front. Python regular expressions, through the built-in re module, describe patterns like this in one short string.

Regular expressions (regex for short) look like gibberish at first: \d{6} or [\w.]+@\w+. That's honestly the hardest part. Once you can read about ten symbols, you can find, check, extract and replace almost any text pattern. This lesson builds them up one symbol at a time.

What you need first: Python strings and cleaning and splitting text.

Key terms

  • Regular expression (regex): a pattern that describes a set of strings, like "six digits in a row".
  • Match: a piece of text that fits the pattern.
  • Metacharacter: a symbol with a special meaning in a pattern, like ., * or \d.
  • Raw string: a string written with r in front, like r"\d+". Python leaves its backslashes alone, which regex needs.
  • Group: part of a pattern inside round brackets ( ), which you can pull out separately.

Your first regular expression in Python

import re

text = "Call me on 9876543210 or the office on 2245678901."
print(re.findall(r"\d{10}", text))
['9876543210', '2245678901']

\d means "any digit" and {10} means "exactly 10 of the thing before". So \d{10} means ten digits in a row. re.findall returns every match as a list.

Always write patterns as raw strings (r"..."). In a normal string, Python treats \ as the start of things like \n (new line) before re ever sees it. Raw strings avoid that whole class of bugs.

The symbols you need most

Learn these and you can read most patterns you'll meet:

SymbolMatchesExample patternMatches in text
\dOne digit, 0 to 9\d\d42
\wOne letter, digit or underscore\w+Ahana_21
\sOne whitespace charactera\sba b
.Any character except a new linec.tcat, cut, c9t
[abc]One of a, b or c[aeiou]e
[a-z]One character in the range[A-Z]P
[^abc]One character that's not a, b or c[^0-9]x
\D, \W, \SThe opposite of \d, \w, \s\D+abc
^Start of the string^HiHi at the start only
$End of the string\.pdf$.pdf at the end only
\bWord boundary, the edge of a word\bcat\bcat, not in catch
\Escape: treat the next symbol literally\.a real full stop

And these say how many of the previous thing:

SymbolMeansExampleMatches
*0 or moreab*a, ab, abbb
+1 or more\d+7, 2026
?0 or 1 (optional)colou?rcolor, colour
{n}Exactly n\d{6}411001
{n,m}Between n and m\d{2,4}42, 2026

Read a pattern out loud, piece by piece. [A-Z]{5}\d{4}[A-Z] reads "five capital letters, four digits, one capital letter": the shape of an Indian PAN number, such as ABCDE1234F.

The four functions in the re module

import re

text = "Order 1042 cost ₹450, order 1043 cost ₹1200."

print(re.search(r"\d+", text))          # first match, as a Match object
print(re.findall(r"₹(\d+)", text))      # every match (just the group)
print(re.sub(r"\d{4}", "####", text))   # replace every match
print(re.split(r"[,.]\s*", text))       # split wherever the pattern matches
<re.Match object; span=(6, 10), match='1042'>
['450', '1200']
Order #### cost ₹450, order #### cost ₹####.
['Order 1042 cost ₹450', 'order 1043 cost ₹1200', '']
FunctionReturnsUse it to
re.search(p, s)The first match, or NoneCheck if a pattern appears anywhere, and get it
re.match(p, s)A match only at the start of s, or NoneCheck how a string begins
re.fullmatch(p, s)A match only if the whole of s fitsValidate input, like a PIN code
re.findall(p, s)A list of all matchesExtract every number, email, hashtag
re.sub(p, new, s)A new string with matches replacedClean or hide text
re.split(p, s)A list of piecesSplit on several different delimiters

Notice ₹1200 became ₹#### in the sub line: \d{4} matched the first four digits of 1200 too. Patterns match wherever they can, which often catches more than you meant. Test them on real examples.

Using the Match object

search returns a Match object, or None if nothing matched. Always check for None before using it:

import re

m = re.search(r"\d{6}", "Ship to MG Road, Pune 411001, India")
if m:
    print(m.group(), m.start(), m.end())
else:
    print("No PIN code found")
411001 22 28

m.group() is the matched text; start() and end() are its positions. If you skip the if and nothing matches, you get AttributeError: 'NoneType' object has no attribute 'group', one of the most common regex errors.

Validating input with fullmatch

To check that the whole input fits a pattern, use fullmatch. search would accept "abc411001xyz" as a PIN code because it contains six digits.

import re

def is_pin_code(text):
    return re.fullmatch(r"[1-9]\d{5}", text) is not None

for value in ["411001", "011001", "41100", "abc411001xyz"]:
    print(value, is_pin_code(value))
411001 True
011001 False
41100 False
abc411001xyz False

Indian PIN codes are six digits and don't start with 0, so the first digit is [1-9].

Groups: pulling out parts of a match

Round brackets mark a group. Each group can be read on its own:

import re

m = re.search(r"(\d{2})-(\d{2})-(\d{4})", "Exam on 15-03-2027 at 10 am")
print(m.group(0))
print(m.group(1), m.group(2), m.group(3))
day, month, year = m.groups()
print(year)
15-03-2027
15 03 2027
2027

group(0) is the whole match. When a pattern has groups, findall returns the groups instead of the whole match, as a list of tuples if there's more than one:

import re

text = "Ahana: 88, Rohan: 72, Meera: 95"
print(re.findall(r"(\w+): (\d+)", text))
[('Ahana', '88'), ('Rohan', '72'), ('Meera', '95')]

That turns straight into a dictionary with dict(...).

Named groups make long patterns readable: (?P<name>...).

import re

m = re.search(r"(?P<user>[\w.]+)@(?P<domain>[\w.]+)", "Mail ahana.khan@college.edu.in today")
print(m.group("user"), m.group("domain"))
ahana.khan college.edu.in

Practical patterns

Indian mobile numbers

Mobile numbers have 10 digits and start with 6, 7, 8 or 9. People add +91, spaces or dashes. This pattern allows an optional +91 and an optional space or dash after the first five digits:

import re

messages = "Reach me at +91 98765 43210, or 7012345678. Office: 020-2567890."
pattern = r"(?:\+91[\s-]?)?([6-9]\d{4})[\s-]?(\d{5})"
numbers = [a + b for a, b in re.findall(pattern, messages)]
print(numbers)
['9876543210', '7012345678']

(?: ... ) is a group that groups without capturing, used here so +91 is optional but not returned. The office landline doesn't start with 6 to 9 in the right place, so it's skipped.

Emails

A complete email pattern is very long. This simple one is good enough for extracting emails from text:

import re

text = "Contact ahana.khan@gmail.com or support@shop.co.in for help."
print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.-]+", text))
['ahana.khan@gmail.com', 'support@shop.co.in']

Don't use regex alone to decide whether an email is real. The only reliable check is sending a confirmation email.

Hiding sensitive numbers

sub can use groups in the replacement with \1, \2 and so on. This keeps the last four digits of a card or Aadhaar-style number and hides the rest:

import re

text = "Card 4111 1111 1111 1234 was charged."
print(re.sub(r"\d{4} \d{4} \d{4} (\d{4})", r"XXXX XXXX XXXX \1", text))
Card XXXX XXXX XXXX 1234 was charged.

Greedy and lazy matching

* and + are greedy: they grab as much text as they can. This catches everyone out with HTML-like text:

import re

html = "<b>Price</b> and <b>Offer</b>"
print(re.findall(r"<b>(.*)</b>", html))
print(re.findall(r"<b>(.*?)</b>", html))
['Price</b> and <b>Offer']
['Price', 'Offer']

Adding ? after * or + makes it lazy: as little as possible. (For real HTML, use a parser such as Beautiful Soup, not regex.)

Flags and compiled patterns

Flags change how a pattern behaves. re.IGNORECASE (or re.I) ignores case:

import re

print(re.findall(r"python", "Python, PYTHON and python", flags=re.IGNORECASE))
['Python', 'PYTHON', 'python']

If you use the same pattern many times, compile it once with re.compile. It reads well and gives your pattern a name:

import re

PIN_CODE = re.compile(r"\b[1-9]\d{5}\b")
addresses = ["Pune 411001", "Delhi 110001", "No pin here"]
for a in addresses:
    m = PIN_CODE.search(a)
    print(m.group() if m else None)
411001
110001
None

Where regular expressions are used

  • Data cleaning in pandas: df["phone"].str.replace(r"\D", "", regex=True) strips non-digits from a whole column.
  • Log analysis: pulling dates, IP addresses and error codes out of server logs.
  • Web scraping: finding prices or dates in scraped text.
  • Form validation on websites, in both Python and JavaScript, which share most of this syntax.

Common mistakes

  • Forgetting the r before the pattern string.
  • Not escaping ., which matches any character. \. matches a real full stop.
  • Using search to validate. It accepts input with extra text around the match. Use fullmatch.
  • Calling .group() on None. Check the result first.
  • Writing one giant pattern. Build and test it in small parts. Sites like regex101.com show what each part matches; set the flavour to Python.

Practice

  1. Find all the hashtags in "Loving #Python and #DataScience at #PyConIndia2026!".
Show the answer

# followed by one or more word characters:

import re

print(re.findall(r"#\w+", "Loving #Python and #DataScience at #PyConIndia2026!"))
['#Python', '#DataScience', '#PyConIndia2026']
  1. Write a pattern that checks a PAN number: 5 capital letters, 4 digits, 1 capital letter. Test it on "ABCDE1234F" and "ABCD1234F".
Show the answer
import re

for pan in ["ABCDE1234F", "ABCD1234F"]:
    print(pan, re.fullmatch(r"[A-Z]{5}\d{4}[A-Z]", pan) is not None)
ABCDE1234F True
ABCD1234F False
  1. Replace every run of spaces in "too many spaces" with one space.
Show the answer
import re

print(re.sub(r" +", " ", "too    many   spaces"))
too many spaces

\s+ would also replace tabs and new lines.

  1. Extract every price as a number from "Tea ₹20, Coffee ₹45.50, Thali ₹180", and add them up.
Show the answer

Make the decimal part optional with (?:\.\d+)?:

import re

menu = "Tea ₹20, Coffee ₹45.50, Thali ₹180"
prices = [float(p) for p in re.findall(r"₹(\d+(?:\.\d+)?)", menu)]
print(prices, sum(prices))
[20.0, 45.5, 180.0] 245.5
  1. Change dates from DD/MM/YYYY to YYYY-MM-DD in "Joined 05/08/2024, left 31/01/2026".
Show the answer

Capture the three parts and reorder them with \3-\2-\1:

import re

text = "Joined 05/08/2024, left 31/01/2026"
print(re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\2-\1", text))
Joined 2024-08-05, left 2026-01-31

Interview questions

What is the difference between re.match, re.search and re.fullmatch?

match only looks for a match at the start of the string. search looks anywhere and returns the first match. fullmatch succeeds only if the entire string matches the pattern, which makes it the right choice for validation.

What is the difference between greedy and lazy quantifiers?

Greedy quantifiers (*, +, ?, {m,n}) match as much text as possible while still letting the overall pattern match. Adding ? (*?, +?) makes them lazy, matching as little as possible.

Why should regex patterns be raw strings in Python?

Without r, Python processes backslash escapes first, so "\b" becomes a backspace character instead of the regex word boundary. A raw string passes the backslashes to re unchanged.

Key takeaways

  • Write patterns as raw strings: r"\d{6}".
  • \d, \w, \s, ., [...] match one character; *, +, ?, {n} say how many.
  • findall extracts, sub replaces, split splits, search finds the first match, fullmatch validates.
  • Round brackets create groups; findall returns the groups when there are any.
  • .* is greedy; .*? is lazy. Escape a real dot as \..
  • Always check that search didn't return None before calling .group().

Frequently asked questions

Is the re module built into Python?

Yes. re is part of the standard library, so import re works without installing anything. The full syntax is in the official documentation at docs.python.org/3/library/re.html.

When should I not use regular expressions?

When a plain string method does the job (startswith, in, split), because it's clearer and faster. Also avoid regex for nested formats like HTML and JSON; use a proper parser.

How do I match a special character like + or ( literally?

Put a backslash in front: \+, \(, \.. Or use re.escape(text) to escape a whole string automatically.

What to learn next

  1. Understand characters like ₹ and Hindi letters in Unicode and text encodings in Python.
  2. Practise everything in Python string practice: 15 problems.
  3. Revise the simpler tools in cleaning and splitting text.