Enter a regular expression pattern and a string to test it against.
Regular expressions are powerful tools for pattern matching and text manipulation. They allow us to search, match, and manipulate strings based on specific patterns.
The re
module is used to work with regular expressions. Here's an example that demonstrates how to use regex with capturing groups:
import re # Match a pattern and capture groups text = "Hello, my name is Alice. I am 25 years old." pattern = r"Hello, my name is (\w+). I am (\d+) years old." match = re.search(pattern, text) if match: name = match.group(1) age = match.group(2) print(f"Name: {name}") print(f"Age: {age}")
In this code, we import the re
module and define a pattern using a raw string (r"..."
). The pattern includes capturing groups denoted by parentheses (...)
.
We use re.search()
to search for the pattern within the text
string. If a match is found, we can access the captured groups using the group()
method on the match
object. The captured groups are numbered starting from 1.
The output of the code will be:
Name: Alice
Age: 25
In this example, we match the pattern "Hello, my name is (\w+). I am (\d+) years old."
against the text
string. The first capturing group (\w+)
captures the name, and the second capturing group (\d+)
captures the age.
By using capturing groups, you can extract specific parts of a matched pattern and use them for further processing or manipulation.
Regular expressions offer a wide range of features and syntax for pattern matching, including character classes, quantifiers, anchors, and more. You can refer to the Python documentation for more information on regular expressions and their syntax.