Java Regex 中捕捉组和返回引用
捕获组是一种将多个字符视作单一单元的方式。通过将要分组的字符放在一对括号中创建它们。例如,正则表达式 (dog) 创建一个包含字母“d”、“o”和“g”的单一组。
捕获组按从左到右的顺序对其左括号进行计数来编号。
例如,在表达式 ((A)(B(C))) 中,有四个这样的组 -
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
返回引用允许使用一个数字(其中 # 表示组)重复使用捕获组,例如#。
请参阅以下示例 −
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tester {
public static void main(String[] args) {
//2 followed by 2 five times
String test = "222222";
String pattern = "(\d\d\d\d\d)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(test);
if (m.find( )) {
System.out.println("Matched!");
}else {
System.out.println("not matched!");
}
//\1 as back reference to capturing group (\d)
pattern = "(\d)\1{5}";
r = Pattern.compile(pattern);
m = r.matcher(test);
if (m.find( )) {
System.out.println("Matched!");
}else {
System.out.println("not matched!");
}
}
}输出
Matched! Matched!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP