Ticker

6/recent/ticker-posts

Regex in Python

Regex in Python

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.

python
import re

Matching
You can use re.match() to check if a pattern exists at the beginning of a string.

python
pattern = r"hello"
text = "hello, world!"
match = re.match(pattern, text)
if match:
print("Pattern found!")
else:
print("Pattern not found.")

Search
re.search() finds the first occurrence of a pattern in a string.

python
pattern = 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 All
re.findall() returns all occurrences of a pattern as a list.

python
pattern = r"\d+"
text = "The price is $20, and $50 for two."
numbers = re.findall(pattern, text)
print("Found numbers:", numbers)

Substitution
re.sub() allows you to replace patterns with a specified string.

python
pattern = 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.

python
pattern = 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.

python
pattern = 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.

Post a Comment

0 Comments