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