Python Regular Expressions (RegEx)
A regular expression, or RegEx, is a sequence of characters that defines a search pattern. Python’s re
module provides functions for working with regular expressions.
1. Matching Patterns
The re.match()
function searches for a pattern at the beginning of a string.
Example:
import re
pattern = r"hello"
text = "hello world"
match = re.match(pattern, text)
if match:
print("Pattern found!")
else:
print("Pattern not found!")
2. Searching Patterns
The re.search()
function searches for a pattern anywhere in a string.
Example:
pattern = r"world"
text = "hello world"
match = re.search(pattern, text)
if match:
print("Pattern found!")
else:
print("Pattern not found!")
3. Finding All Matches
The re.findall()
function finds all occurrences of a pattern in a string and returns them as a list.
Example:
pattern = r"lo"
text = "hello world"
matches = re.findall(pattern, text)
print(matches) # Output: ['lo', 'lo']
4. Substituting Patterns
The re.sub()
function substitutes occurrences of a pattern in a string with another string.
Example:
pattern = r"world"
text = "hello world"
new_text = re.sub(pattern, "Python", text)
print(new_text) # Output: hello Python
Conclusion
Regular expressions are a powerful tool for pattern matching and text manipulation in Python. The re
module provides functions for searching, matching, finding all occurrences, and substituting patterns in strings.