How to Use Groups to Retrieve Parts of Regular Expression Matches in Python 


               


How to Use Groups to Retrieve Parts of Regular Expression Matches in Python



Python


In this article, we show how to use groups to retrieve parts of regular expression matches in Python.

So say, we have a program that asks for a user's birth date.

We want the birth date entered in with the format mm-dd-yyyy.

We can have a regular expression that separates the month, the day, and the year.

We can then use groups in order to output each part: the month, the day, and the year.

So let's see how this would work in actual Python code.

This is shown in the code below.



So let's now go over this code.

re is the module in Python that allows us to use regular expressions. So we first have to import re in our code, in order to use regular expressions.

After this, we have a variable, birthdate, which is set equal to a birth date, in this case June 15, 1987.

We then have a variable, regex, which is set equal to, re.search(r"(\d{1,2})-(\d{1,2})-(\d{4})", birthdate)

This regular expression is set equal to a raw string which has a first digit that is 1 or 2 digits long (the month). This is followed by a dash (-). The second digit is also 1 or 2 digits long (the day). This is followed by a dash (-). The third digit is 4 digits long (the year).

We then print out the complete birth date with the statement, regex.group()

regex.group() returns the complete matches of all the matches from the regular expression.

Notice in the regular expression, we have various parentheses throughout the regular expression. These parentheses create the different subdivisions that produce the different parts of the group. Notice that there are 3 opening and closing parentheses in the regular expression, which creates 3 different matches. Thus, the first parentheses refers to, regex.group(1), which is the month. The second parentheses refers to, regex.group(2), which is the day. The third parentheses refers to, regex.group(3), which is the year.

And this is how we can use groups to retrieve parts of regular expression matches in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...