Java 正则表达式中非捕获组
使用捕获组,你可以将多个字符视为一个单元。你只需要将需要分组的字符放在一组括号内。例如 −
(.*)(\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
非捕获组
非捕获组提供与捕获组相同的功能,但它不会捕获结果
例如,如果你需要使用组从文本中匹配网址或电话号码,因为所需子字符串的起始部分是相同的,所以你不需要捕获某些组的结果,在这种情况下,你可以使用非捕获组。非捕获组以 (?: 开始,以 ) 结束。
示例
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
注意: 非捕获组不会包含在组计数中。
广告