Java 获取在正则表达式中进行匹配的组的编号/id
我写了两个小时的代码,认为Java 获取在正则表达式中进行匹配的组的编号/id,java,regex,Java,Regex,我写了两个小时的代码,认为Matcher.group()返回了在regex中进行匹配的组的编号/id。我所做工作的简化示例: // Group -1- -2- Pattern p = Pattern.compile("(abc)|(def)"); String t = "abc abc def def abc"; for (Matcher m = p.matcher(t); m.find(); ) { System.out.print( m.group() ); }
Matcher.group()
返回了在regex中进行匹配的组的编号/id。我所做工作的简化示例:
// Group -1- -2-
Pattern p = Pattern.compile("(abc)|(def)");
String t = "abc abc def def abc";
for (Matcher m = p.matcher(t); m.find(); ) {
System.out.print( m.group() );
}
我想这会输出
1,1,2,2,1
,每个匹配的组数。相反,它实际上返回组匹配的部分。是否有任何其他方法或方法可以达到我想要的结果?您可以检查组的结果,查看哪一个结果是匹配的:
for (Matcher m = p.matcher(t); m.find(); ) {
if (m.group(1) != null) {
System.out.print("1, ");
} else {
System.out.print("2, ");
}
}
编辑:如果您有很多组,并且不想硬编码它们,您可以在它们上面循环(假设它们仍然是独占的):
for(Matcher m=p.Matcher(t);m.find();){
对于(int i=1;i您可以检查组
结果,查看哪一个匹配:
for (Matcher m = p.matcher(t); m.find(); ) {
if (m.group(1) != null) {
System.out.print("1, ");
} else {
System.out.print("2, ");
}
}
编辑:如果您有很多组,并且不想硬编码它们,您可以在它们上面循环(假设它们仍然是独占的):
for(Matcher m=p.Matcher(t);m.find();){
对于(int i=1;i Pattern类型不匹配:无法从字符串转换为模式
?Pattern类型不匹配:无法从字符串转换为模式
?我考虑过这个问题,但您知道,我的正则表达式非常大(>1000个字符)我的文本也是如此,时间是一个问题。它会对性能产生多大影响吗?21个组我考虑过,但你看,我的正则表达式非常大(>1000个字符),我的文本也是如此,时间是一个问题。它会对性能产生多大影响吗?21个组