Skip to content

Java RegEx – Matching Groups

Java RegEx – Matching Groups example shows how to match groups in Java regular expression. Capturing groups in a regex can be done using brackets.

How to match groups in a regex pattern in Java?

Capturing groups in regex is an important function and can be very useful in extracting data from the string content. A group in regex is a group of characters and it is defined using the opening and closing parenthesis, “(” and “)”. Matched groups in the content are stored for later reference.

Here is a simple example of matching a group of digits in a string.

Output

As you can see from the output, we have captured two numbers from the string using regex groups. The group method of the Matcher class returns the captured group by the specified number.

The group number starts from 1 while the group 0 is a special group that represents the entire expression.

We can also nest the groups inside other groups like (a(b(c)). There are 3 groups in this expression. The groups are counted from the left to the right. So in this expression the group 1 is (a(b(c)), group 2 is (b(c)), and group 3 is (c).

Output

How to get the start and end index of captured groups?

The start and end methods of the Matcher class return the start and end index of the matched group respectively.

This method returns the start index of the most recent match.

This method returns the end index of the most recent match.

Example:

Output

The captured groups can be referenced using the “\” followed by the group number. Please see below example for understating how to reference the groups.

Ouput

In this example, I have referenced the group (at) using group reference “\1”. The pattern “c(at) & kitk(\\1)” is same as the pattern “c(at) & kitk(at)”.

If you learn more about regex, visit the Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.