使用捕获组,您可以将多个字符视为一个单元。您只需要将要分组的字符放在一组括号内即可。例如-
(.*)(\\d+)(.*)
如果您要匹配多个组,则将捕获每个组的匹配结果。您可以通过将其各自的组号传递给group()方法来获得一个组的结果。1,2,3等。(从右到左)组0表示整个匹配。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroups { public static void main( String args[] ) { System.out.println("Enter input text"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "(.*)(\\d+)(.*)"; //Create a Pattern object Pattern pattern = Pattern.compile(regex); //Now create matcher object. Matcher matcher = pattern.matcher(input); if (matcher.find( )) { System.out.println("Found value: " + matcher.group(0) ); System.out.println("Found value: " + matcher.group(1) ); System.out.println("Found value: " + matcher.group(2) ); System.out.println("Found value: " + matcher.group(3) ); } else { System.out.println("NO MATCH"); } } }
Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle
非捕获组提供与捕获组相同的功能,但不捕获结果
例如,如果您需要使用组来匹配文本中的URL或电话号码,由于所需子字符串的开头部分相同,因此您无需捕获某些组的结果,在这种情况下,您可以使用非捕获组。非捕获组以(?:开头,以)结尾。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroups { public static void main( String args[] ) { System.out.println("Enter input text"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "(.*)(?:\\d+)(.*)"; //Create a Pattern object Pattern pattern = Pattern.compile(regex); //Now create matcher object. Matcher matcher = pattern.matcher(input); if (matcher.find( )) { System.out.println("Found value: " + matcher.group(0) ); System.out.println("Found value: " + matcher.group(1) ); System.out.println("Found value: " + matcher.group(2) ); } else { System.out.println("NO MATCH"); } } }
Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: (digits) in middle
注意:非捕获组将不包括在组计数中。