In regular expressions, you can use numbered capturing groups to capture and retrieve specific parts of a pattern match. A numbered group is created by placing parentheses around a pattern. For example, the regular expression pattern (\d\d)-(\d\d)-(\d\d\d\d) captures a date in the format of dd-mm-yyyy, with each digit represented by a numbered group.
Here's an example of using numbered groups in Python's re module:
import retext = "My favorite numbers are 42 and 123."pattern = r"My favorite numbers are (\d+) and (\d+)\."match = re.search(pattern, text)if match: print(match.group(0)) # entire match print(match.group(1)) # first numbered group print(match.group(2)) # second numbered group |
In this example, the regular expression pattern captures two numbers, which are stored in the first and second numbered groups. The search() function searches the input string for a match to the pattern, and the group() method retrieves the captured groups.
The output of this program is:
|
|
As you can see, the group() method retrieves the entire matched string, as well as each numbered capturing group.
You can also use named groups in Python's re module, which allows you to give each group a descriptive name that you can use to retrieve the captured text. Named groups are created by placing (?P<name>...) around a pattern, where name is the name of the group and ... is the pattern to capture.
Here's an example of using named groups:
import retext = "My favorite numbers are 42 and 123."pattern = r"My favorite numbers are (?P<number1>\d+) and (?P<number2>\d+)\."match = re.search(pattern, text)if match: print(match.group(0)) # entire match print(match.group('number1')) # named group 'number1' print(match.group('number2')) # named group 'number2' |
In this example, the regular expression pattern captures two numbers using named groups, which are named number1 and number2. The search() function searches the input string for a match to the pattern, and the group() method retrieves the captured groups using their respective names.
The output of this program is the same as the previous example:
|
|
As you can see, the group() method can retrieve captured text using either numbered or named groups, depending on how the groups were defined in the regular expression pattern.