The concept of capturing groups in a Java regular expression (go)

Source: Internet
Author: User

To figure out these three methods, you first need to understand the concept of capturing groups in a Java regular expression. The capturing group is also the sub-pattern of the pattern in parentheses to "()". The main reason to use capturing groups is to find out what you care more about in a match.
Capturing groups can be numbered by calculating their opening brackets from left to right. For example, in an expression "(x) (y\\w*) (z)", there are three such groups:
1. x
2. y\\w*
3. Z
Group 0 always represents an entire expression.
This is why the capturing group is named because in the match, each subsequence of the input sequence that matches these groups is saved. The captured subsequence can later be used in an expression through the back reference, or it can be obtained from the match after the match operation is complete.
A group that begins with a (?) is a pure, non-capturing group that does not capture text and does not count against group totals.

Example:

Package pattern;

Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

public class Testregex {
public static void Main (string[] args) {
String regex = "(x) (y\\w*) (z)";

String input = "exy123z,xy456z";
Pattern p = pattern.compile (regex, pattern.case_insensitive);
Matcher m = p.matcher (input);

while (M.find ()) {
System.out.println (M.group (2));
}
}
}

Operation Result:
Y123
y456

http://blog.163.com/[email protected]/blog/static/1662603142011219625597/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.