我有一个包含多个捕获组的正则表达式:
String regex = "(first|second|third)|(one|two|three)|(uno|dos|tres)";
我可以遍历一个String
,从每个组中查找模式:
String text = "one two uno third second tres";
Matcher matcher = Pattern.compile(regex).matcher(text);
for(int index = 0; matcher.find(index); index = matcher.end()) {
System.out.println(matcher.group());
}
问题是,它没有告诉我它来自哪个组。
我可以将找到的组与每个可用组的 matcher.group(#)
进行比较,然后选择不返回 null
的组:
int numOfGroups = 3;
for(int index = 0; matcher.find(index); index = matcher.end()) {
String result = null;
int group = 0;
for(int i = 1; i <= numOfGroups; i++) {
String tmp = matcher.group(i);
if(tmp != null) {
result = tmp;
group = i;
break;
}
}
System.out.println(result + " " + group);
}
但这会增加每次迭代最多 3 个步骤(3 组)的时间复杂度。
我如何确定哪个组触发了比赛?
最佳答案
一组 Matcher
怎么样,每个 Pattern
一个?您不会识别哪个组触发了匹配,而是识别了哪个 Matcher
具有匹配。
public static void main(String[] args) throws Exception {
String text = "one two uno third second tres";
Matcher[] matcher = {
Pattern.compile("(first|second|third)").matcher(text),
Pattern.compile("(one|two|three)").matcher(text),
Pattern.compile("(uno|dos|tres)").matcher(text)
};
for (int i = 0; i < matcher.length; i++) {
while (matcher[i].find()) {
System.out.println(matcher[i].group() + " " + i);
}
}
}
结果:
third 0
second 0
one 1
two 1
uno 2
tres 2
关于java - 查找 Matcher 找到匹配的捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361350/