Group of Java Regular Expressions ()

Source: Internet
Author: User

Using regular expressions in Java to return a string that matches a regular expression uses group (), which records all the strings that match the specified expression, and I'll explain how to use the group in a piece of code:

public static void main(String[] args)
{

Pattern p = Pattern.compile("(file://\\d+,)(/\\d+)");
String s = "123,456-34,345";
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println("m.group():"+m.group()); //打印所有

System.out.println("m.group(1):"+m.group(1)); //打印数字的

System.out.println("m.group(2):"+m.group(2)); //打印字母的
System.out.println();
}

System.out.println("捕获个数:groupCount()="+m.groupCount());
}

You first create the pattern object, where you compile the expression you want to use, and then use the Matcher method to match the specified expression in the string, and then you output the lookup result. Before calling M.group, it is important to remember to call M.find, or else you will generate a compilation error, in the regular expression, in parentheses, the group (0) is equivalent to group (), representing the matching string for the entire regular expression, group (1) Equivalent to the string returned by the expression in the first parenthesis, and so on. When the while loop executes a round, the second round outputs the second set of matching strings. The results of the above procedures are as follows:m.group():123,456
m.group(1):123,
m.group(2):456

m.group():34,345
m.group(1):34,
m.group(2):345

Number of captures:

GroupCount () =2

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.