Introduction
Regular expressions (regex) are powerful tools for pattern matching and text manipulation in Python. They allow you to find, replace, and extract specific patterns of characters within strings.
Basic Syntax
To use regex in Python, you need to import the re
module.
pythonimport re
Matching
You can use re.match()
to check if a pattern exists at the beginning of a string.
pythonpattern = r"hello"
text = "hello, world!"
match = re.match(pattern, text)
if match:
print("Pattern found!")
else:
print("Pattern not found.")
Searchre.search()
finds the first occurrence of a pattern in a string.
pythonpattern = r"world"
text = "hello, world!"
match = re.search(pattern, text)
if match:
print("Pattern found at index:", match.start())
else:
print("Pattern not found.")
Find Allre.findall()
returns all occurrences of a pattern as a list.
pythonpattern = r"\d+"
text = "The price is $20, and $50 for two."
numbers = re.findall(pattern, text)
print("Found numbers:", numbers)
Substitutionre.sub()
allows you to replace patterns with a specified string.
pythonpattern = r"\d+"
text = "The price is $20, and $50 for two."
new_text = re.sub(pattern, "X", text)
print("Modified text:", new_text)
Flags
Flags modify regex behavior, e.g., re.IGNORECASE
for case-insensitive matching.
pythonpattern = r"apple"
text = "An APPLE a day keeps the doctor away."
match = re.search(pattern, text, re.IGNORECASE)
if match:
print("Pattern found:", match.group())
Grouping
You can use parentheses to create groups for more complex patterns.
pythonpattern = r"(apple|orange) juice"
text = "I like apple juice and orange juice."
match = re.search(pattern, text)
if match:
print("Pattern found:", match.group())
print("Fruit:", match.group(1))
Conclusion
Regex in Python provides a powerful and flexible way to work with text data, enabling you to perform various operations like matching, searching, and substitution based on specific patterns.
Please note that the above examples are just basic illustrations. Regular expressions can become complex, so it's essential to refer to the Python re
module documentation for more in-depth details and advanced usage.
0 Comments