Java
Regex
Capturing Groups
Regular Expressions
Programming

Java Regex Capturing Groups

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java Regular Expressions (Regex) are a powerful tool for pattern matching and data extraction in strings. Capturing groups are one of the core features that allow developers to extract specific segments of matched text. This article provides a detailed exploration of capturing groups in Java Regex, including technical explanations, examples, and some best practices.

Understanding Capturing Groups

Capturing groups in regex are denoted by parentheses (). They serve to:

  1. Define a subpattern, allowing you to extract parts of the matching string.
  2. Apply quantifiers to entire patterns.
  3. Create backreferences that can be used within regular expressions for repeated patterns.

Basic Syntax

In Java Regex, capturing groups are numbered by counting their opening parentheses from left to right, starting at 1. The full match is always group 0.

Example Pattern: (abc)

java
1import java.util.regex.*;
2
3public class CapturingGroupsExample {
4    public static void main(String[] args) {
5        String text = "abc def abc";
6        Pattern pattern = Pattern.compile("(abc)( def)");
7        Matcher matcher = pattern.matcher(text);
8
9        while (matcher.find()) {
10            System.out.println("Full match: " + matcher.group(0));
11            System.out.println("Group 1: " + matcher.group(1));
12            System.out.println("Group 2: " + matcher.group(2));
13        }
14    }
15}

Output:

 
1Full match: abc def
2Group 1: abc
3Group 2:  def
4Full match: abc
5Group 1: abc
6Group 2: null

From this example, note that:

  • matcher.group(0) returns the entire match.
  • matcher.group(1) and matcher.group(2) return their respective groups.

Named Capturing Groups

Java 7 introduced named capturing groups, which give more clarity, especially in complex regex patterns. Named groups are defined with (?<name>...) syntax.

Example:

java
1import java.util.regex.*;
2
3public class NamedGroupsExample {
4    public static void main(String[] args) {
5        String text = "John Doe, ID: 12345";
6        Pattern pattern = Pattern.compile("(?<name>[A-Za-z]+) (?<surname>[A-Za-z]+), ID: (?<id>\\d+)");
7        Matcher matcher = pattern.matcher(text);
8
9        if (matcher.find()) {
10            System.out.println("Name: " + matcher.group("name"));
11            System.out.println("Surname: " + matcher.group("surname"));
12            System.out.println("ID: " + matcher.group("id"));
13        }
14    }
15}

Output:

 
Name: John
Surname: Doe
ID: 12345

Non-Capturing Groups

Sometimes, you may want to group subpatterns without capturing them. This is achieved using (?:...). These groups are useful when you want to apply operators to a group of elements without saving the match.

Example: (a|b|c) can be written as (?:a|b|c) if you only need the alternation without capture.

Backreferences

Backreferences allow you to refer to captured groups later in the regex using \1, \2, etc., based on the group number. For named groups, you use \k<name>.

Example:

java
1import java.util.regex.*;
2
3public class BackreferenceExample {
4    public static void main(String[] args) {
5        String text = "ababab";
6        Pattern pattern = Pattern.compile("(ab)\\1\\1");
7        Matcher matcher = pattern.matcher(text);
8
9        if (matcher.matches()) {
10            System.out.println("Pattern matches the entire string!");
11        }
12    }
13}

Output:

 
Pattern matches the entire string!

Summary Table

FeatureSyntaxDescription
Capturing Group(pattern)Saves the matched portion for later retrieval.
Named Capturing Group(?<name>pattern)Captures the match and assigns it a name for easier access.
Non-Capturing Group(?:pattern)Groups elements without capturing.
Backreference\\n, \k<name>Refers to a previously captured group by number or name.
Full Match Retrievalmatcher.group(0)Returns the entire matched string.

Practical Considerations

  • Performance: Using excessively many capturing groups can affect performance and may complicate pattern logic.
  • Complex Patterns: In complex regexes, prefer named groups for readability.
  • Regex Testing: Always test your regex with various inputs to ensure they capture precisely what you expect.

Incorporating capturing groups into your Java applications can greatly enhance your ability to parse and manipulate strings efficiently. Understanding their syntax and application opens up a range of capabilities from data validation to intricate string manipulation.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.