简体   繁体   English

Java正则表达式捕获组

[英]java regex capture group

I am trying to capture the right part after the : using java expr, but in the following code, the printed capture group is the whole string, what's wrong? 我正在尝试使用Java expr在:之后捕获正确的部分,但是在以下代码中,打印的捕获组是整个字符串,怎么了?

String s ="xyz: 123a-45";   
String patternStr="xyz:[ \\t]*([\\S ]+)";
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher(s);
//System.err.println(s);
if(m.find()){
    int count = m.groupCount();
    System.out.println("group count is "+count);
    for(int i=0;i<count;i++){
        System.out.println(m.group(i));
    }
}

Numbering of subgroups starts with 1, 0 is the full text. 子组的编号从1开始,全文为0。 Just go till count+1 with your loop. 只需循环执行count + 1即可。

This is because group's indices are starting with 1. Group 0 is the entire pattern. 这是因为组的索引从1开始。组0是整个模式。

From the JavaDoc: "Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group()." 在JavaDoc中:“捕获组是从左到右,从一个索引开始。组零表示整个模式,因此表达式m.group(0)等效于m.group()。” See more here 在这里查看更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM