Python RegEx

1. What is RegEx

Regular Expressions (RegEx) provide a powerful way to search, match, and manipulate text patterns.

import re

text = "Python is powerful"
match = re.search("Python", text)
print(match.group())  # Python

The re module enables pattern-based text processing.


2. Using re.match()

import re

text = "Python Programming"
result = re.match("Python", text)

print(result.group())  # Python

match() checks for a pattern at the start of the string only.


3. Using re.search()

import re

text = "Learn Python Programming"
result = re.search("Python", text)

print(result.group())  # Python

search() scans the entire string for the first match.


4. Using re.findall()

Returns all matches as a list.


5. Using re.sub() (Replace Text)

Replaces matched patterns with new content.


6. Using Character Classes

Common patterns:

  • [a-z] → lowercase letters

  • [A-Z] → uppercase letters

  • [0-9] → digits


7. Metacharacters and Special Sequences

Common sequences:

  • \d → digit

  • \w → alphanumeric

  • \s → whitespace


8. Using Quantifiers

Quantifiers:

  • * → 0 or more

  • + → 1 or more

  • ? → 0 or 1

  • {n} → exact count


9. Grouping with Parentheses

Groups allow segmented extraction of patterns.


10. Real-World RegEx Example (Phone Validation)

Used for input validation and sanitization in production systems.


Common RegEx Patterns Reference

Pattern
Meaning

\d

Digit

\D

Non-digit

\w

Alphanumeric

\W

Non-alphanumeric

^

Start of string

$

End of string

.

Any character

[]

Character set

()

Grouping


Last updated