Regular Expressions (Regex) are one of the most powerful tools in any programmer’s toolkit. In Python, they allow you to search, match, extract, replace, and validate patterns in text.
Whether you're cleaning data, validating user input, or parsing logs—Regex is your go-to tool for text processing.
A Regular Expression is a sequence of special characters that defines a search pattern.
For example:
"a.b"
→ matches any character between a
and b
(like acb
, arb
, etc.)
"\d+"
→ matches one or more digits (like 123
, 42
, etc.)
Python provides the re
module to work with regular expressions.
import re
re
ModuleFunction Description re.search()
Searches for the first match re.match()
Checks for a match only at the beginning re.findall()
Returns all matches as a list re.sub()
Replaces parts of the string re.split()
Splits the string at matches
import re
text = "Contact us at info@example.com"
pattern = r"\w+@\w+\.\w+"
match = re.search(pattern, text)
if match:
print("Found:", match.group())
📤 Output:
Found: info@example.com
Symbol Meaning Example Matches .
Any character a.b
a*b
, a1b
\d
Digit \d+
123
, 42
\w
Word character \w+
abc
, user_1
\s
Whitespace \s+
space, tab ^
Start of string ^Hi
Matches if string starts with Hi
$
End of string end$
Matches if string ends with end
*
0 or more a*
""
, a
, aaa
+
1 or more a+
a
, aa
?
0 or 1 a?
""
, a
[]
Character set [aeiou]
any vowel
OR `cat ()
Grouping (ab)+
abab
import re
number = "9876543210"
pattern = r"^\d{10}$"
if re.match(pattern, number):
print("Valid phone number")
else:
print("Invalid phone number")
📤 Output:
Valid phone number
re.sub()
import re
text = "My email is user123@example.com"
clean_text = re.sub(r"\w+@\w+\.\w+", "[email hidden]", text)
print(clean_text)
📤 Output:
My email is [email hidden]
re.split()
import re
data = "apple,banana;orange|grapes"
fruits = re.split(r"[,;|]", data)
print(fruits)
📤 Output:
['apple', 'banana', 'orange', 'grapes']
Join Anik on Peerlist!
Join amazing folks like Anik and thousands of other people in tech.
Create ProfileJoin with Anik’s personal invite link.
0
11
0