下面这个正则表达式的pattern有两个组,加上默认组应该是三个组,为什么只打印出两组?(\d+)捕获组应该是3000并没有获取到这个捕获组,请问怎么解释?
String string = "This order was placed adefor QT3000! OK?"; String pattern = "(\\D*)(\\d+)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(string); while(m.find()){ System.out.println("找到了"+m.groupCount()); for(int i = 0 ; i < m.groupCount(); i++){ System.out.println("Found value:" + m.group(i)); } }
结果:
找到了2 Found value:This order was placed adefor QT3000 Found value:This order was placed adefor QT
来源http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#groupCount(
public int groupCount()
Returns the number of capturing groups in this matcher's pattern.
Group zero denotes the entire pattern by convention. It is not included in this count.
groupCount() 的计数是不包括 group(0) 的,所以你的循环应该写成(条件是