Python RegEx

🔍 Python RegEx (Regular Expressions)

A Regular Expression (RegEx) is a sequence of characters used to match patterns in text — such as emails, mobile numbers, dates, names, etc.

Python provides a built-in module for RegEx:

import re

✔️ Common RegEx Methods in Python

FunctionDescription
re.search()Searches for the first match
re.findall()Returns all matches
re.match()Checks if the pattern starts at the beginning of the string
re.split()Splits string by pattern
re.sub()Replaces matches

📌 1. re.search() Example

import re

text = “Hello Python Developers!”
match = re.search(“Python”, text)

print(match)


📌 2. re.findall() Example

import re

text = “Apple, Banana, Apple, Mango”
result = re.findall(“Apple”, text)
print(result) # [‘Apple’, ‘Apple’]


📌 3. re.match() Example

import re

text = “Python is fun”
result = re.match(“Python”, text)

print(result)


📌 4. re.split() Example

import re

text = “One,Two,Three,Four”
result = re.split(“,”, text)
print(result)


📌 5. re.sub() Example (Replace Text)

import re

text = “Hello 123 World 456”
result = re.sub(“\d”, “*”, text) # Replace digits
print(result)


🧠 RegEx Metacharacters

PatternMeaningExample
.Any character except newlinehe..o → hello
^Starts with^Hello
$Ends withworld$
*0 or more repetitionsgo* → g, go, gooo
+1 or more repetitionsgo+ → go, goo
?Optionalcolou?r → color, colour
{n}Exactly n occurrences\d{5}
{n,m}Between n and m repetitions\d{2,4}

🔢 Character Classes

PatternMeaning
\dMatches digits (0-9)
\DNon-digit characters
\sSpaces
\SNon-spaces
\wLetters, numbers, underscore
\WAnything except letters/numbers/_

Example:

import re

text = “User123”
print(re.findall(“\d”, text)) # [‘1’, ‘2’, ‘3’]
print(re.findall(“\w”, text)) # [‘U’,’s’,’e’,’r’,’1′,’2′,’3′]


🎯 Using Groups ( )

import re

text = “Price: $150”
result = re.search(“Price: \$(\d+)”, text)
print(result.group(1))


📞 Real-World Examples


✔️ Validate Email

import re

email = “hello@gmail.com”
pattern = r”^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$”

print(bool(re.match(pattern, email)))


✔️ Validate Indian Phone Number

import re

number = “9876543210”
pattern = r”^[6-9]\d{9}$”

print(bool(re.match(pattern, number)))


✔️ Extract All Numbers from Text

import re

text = “My phone is 98765 and zip is 395007”
print(re.findall(“\d+”, text))


✔️ Check If String Only Contains Letters

import re

result = re.match(“^[A-Za-z]+$”, “Python”)
print(bool(result))


📌 Summary Table

TaskFunction
Find first matchre.search()
Find all matchesre.findall()
Check beginning matchre.match()
Replace textre.sub()
Split textre.split()

🧪 Practice Tasks

✔ Find all email addresses in text
✔ Validate password: must include letters, numbers, and symbols
✔ Extract dates (DD/MM/YYYY)

You may also like...