Java Regex Capturing Groups Example

The capturing group's technique allows us to find out those parts of the string that match the regular pattern. The mather's group() method returns the input subsequence captured by the given group during the previous match operation.

Java Regex capturing groups

This example prints all HTML tags from the supplied string by capturing a group of characters.
package net.javaguides.corejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegexGroups {

    public static void main(String[] args) {

        String content = "<p>The <code>Pattern</code> is a compiled " +
            "representation of a regular expression.</p>";

        Pattern p = Pattern.compile("(</?[a-z]*>)");

        Matcher matcher = p.matcher(content);

        while (matcher.find()) {

            System.out.println(matcher.group(1));
        }
    }
}
Output:
<p>
<code>
</code>
</p>

References


Comments