Sometimes you need to extract sub-patterns out of a larger pattern. This can be done by using grouping. Suppose you have textual data with dates in it and you want to extract only the year. from the dates. You can use a regular expression pattern with grouping to match dates and then you can extract the component elements such as the day, month or the year from the date.
Grouping is achieved using the parenthesis operators. Let’s understand grouping using an example.
Let’s say the source string is: “Kartik’s birthday is on 15/03/1995”. To extract the date from this string you can use the pattern – “\d{1,2}\/\d{1,2}\/\d{4}”.
Now to extract the year, you can put parentheses around the year part of the pattern. The pattern is: “^\d{1,2}/\d{1,2}/(\d{4})$”.
Let’s see a demonstration of how to use grouping.
Grouping is a very useful technique when you want to extract substrings from an entire match. Let’s practice some questions on grouping in the following quiz.
You’ve come a long way and learnt almost all important concepts related to regular expressions. In the next section, you’ll see some examples where regular expressions can be used.