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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *