Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取在正则表达式中进行匹配的组的编号/id_Java_Regex - Fatal编程技术网

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个组