Python Regular Expressions
Regular expressions, or regex, provide patterns for searching, extracting, validating, and replacing text. Python provides regex support through the built-in re module.
Search for Text
Python
Find a pattern inside a string.
import re
text = "Python is powerful"
result = re.search("Python", text)
if result:
print("Found")
Common Regex Patterns
TEXT
Common regular expression symbols.
^ Start of string
$ End of string
. Any character
* Zero or more
+ One or more
? Zero or one
\d Digit
\w Word character
\s Whitespace
Find All Matches
Python
Extract all numbers from a string.
import re
text = "Order 123 and order 456"
numbers = re.findall(r"\d+", text)
print(numbers)
Replace Text
Python
Replace matching text with another value.
import re
text = "Python is fun"
result = re.sub(r"fun", "powerful", text)
print(result)
Validate Input
Regular expressions can be used to check whether text follows a required pattern.
Python
Validate a simple numeric string.
import re
value = "12345"
if re.fullmatch(r"\d+", value):
print("Valid number")
else:
print("Invalid number")
Compile a Pattern
Use re.compile() when the same pattern will be reused multiple times.
Python
Create and reuse a compiled regex pattern.
import re
pattern = re.compile(r"\d+")
print(pattern.findall("ID 123, Code 456"))
Summary
Python's re module provides powerful tools for working with text patterns. Use search(), findall(), sub(), fullmatch(), and compile() for common regex tasks.