Home > Java > javaTutorial > How do Capturing Groups Work in Java Regular Expressions?

How do Capturing Groups Work in Java Regular Expressions?

Susan Sarandon
Release: 2024-10-28 22:25:30
Original
692 people have browsed it

How do Capturing Groups Work in Java Regular Expressions?

Understanding Java Regex Capturing Groups

In this code snippet, we use Java's regular expression (regex) library to extract parts of a string. The regex is defined as "(.)(d )(.)", where:

  • (.*): Matches any number of any characters before the next group.
  • (d ): Matches any number of digits after the previous group.
  • (.*): Matches any number of any characters after the previous group.

Regex Execution

When the regex is executed against the string "This order was placed for QT3000! OK?", it produces the following results:

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Copy after login
Copy after login

Understanding Greedy Quantifiers

The default quantifier used in the regex is greedy, meaning it matches as many characters as possible to satisfy the next group. In this case, ".*" matches the entire string until the first digit is found, leaving no characters for the third group.

Using Reluctant Quantifiers

To match only the necessary characters, we can use a reluctant quantifier, indicated by a question mark. Replacing "(.)" with "(.?)" matches the least number of characters possible, resulting in the following output:

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Copy after login
Copy after login

Advantages of Capturing Groups

Capturing groups allow us to extract specific parts of a matching string for further use. In this example, we can access each group's matched value through the "group()" method of the "Matcher" object, as demonstrated in the code snippet below:

<code class="java">Pattern pattern = Pattern.compile("(.*?)(\d+)(.*)");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}</code>
Copy after login

The above is the detailed content of How do Capturing Groups Work in Java Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template