MyInternships.in

Python Advanced

Python Regular Expressions

Regular expressions let you search, match, and replace text using powerful patterns. Python's built-in re module gives you everything you need to work with them.


Importing re

Regular expression support comes from the re module, which is part of Python's standard library, so there is nothing to install. Patterns are written as strings, often as raw strings using an r prefix to avoid escaping backslashes.

Importing re
Python
import re

pattern = r"\d+"  # one or more digits

match(), search() and findall()

match() checks only the beginning of a string, search() scans the whole string for the first match, and findall() returns a list of every match found. All three take the pattern first, then the text.

Finding numbers in text
Python
import re

text = "Order 12 has 5 items and costs 499 rupees"

print(re.match(r"\d+", text))
print(re.search(r"\d+", text).group())
print(re.findall(r"\d+", text))
Output
Output
None
12
['12', '5', '499']

sub() — Search and Replace

The sub() function replaces every match of a pattern with a replacement string, similar to find-and-replace but powered by patterns instead of exact text.

Masking phone numbers
Python
import re

text = "Call me at 9876543210"
masked = re.sub(r"\d{10}", "**********", text)
print(masked)

Common Metacharacters

Regex patterns are built from special characters called metacharacters. Combining them lets you describe very flexible search rules in a single short pattern.

PatternMeaning
.Any character except newline
\dAny digit (0-9)
\wAny word character (letter, digit, _)
\sAny whitespace character
+One or more of the previous
*Zero or more of the previous
?Zero or one of the previous
^Start of string
$End of string
[abc]Any one of a, b, or c
💡

Always use raw strings (prefix with r) for regex patterns so backslashes like \d and \s are passed to re exactly as written.

⚠️

Compile patterns you reuse often with re.compile() for cleaner code and slightly better performance in loops.

Frequently Asked Questions

What is the difference between re.match() and re.search()?+

re.match() only checks for a match at the very start of the string and returns None otherwise. re.search() scans the entire string and returns the first match found anywhere in it.

Why should I use raw strings for regex patterns?+

Raw strings (prefixed with r) stop Python from interpreting backslashes as escape sequences, so patterns like \d or \s reach the re module exactly as you typed them instead of being misread.

How do I extract all matches instead of just the first one?+

Use re.findall(pattern, text), which returns a list of every non-overlapping match in the string, or re.finditer() if you also need position information for each match.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships