最近学习正则表达式,发现Java中的一些术语与其他地方描述的有所差异。比如Java正则表达式中的“组”概念与《正则表达式必知必会》一书中讲述的“子表达式”其实是一样的,只是表述不同而已。由此也引发了使用JavaAPI时对group(int group)、start(int group)、end(int group)不是太理解。在阅读了关于正则表达式问题:有谁用过Matcher类的group()方法没有 之后彻底明白,并写了一个小程序测试。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str="hello world !";
Pattern p=Pattern.compile("w(or)(ld)");
Matcher m=p.matcher(str);
while(m.find()){
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
//System.out.println(m.group(3));//当没有第三个()时,报Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 3异常
- System.out.println("Start 0:"+matcher.start(0)+" End 0:"+matcher.end(0));//总匹配的索引
- System.out.println("Start 1:"+matcher.start(1)+" End 1:"+matcher.end(1));//第一组匹配的索引
- System.out.println("Start 2:"+matcher.start(2)+" End 2:"+matcher.end(2));//第二组匹配的索引
- System.out.println(str.substring(matcher.start(0),matcher.end(1)));//从总匹配开始索引到第1组匹配的结束索引之间子串——Wor
}
}
}
其实group(),start(),end()所带的参数i就是正则表达式中的子表达式索引(第几个子表达式),由于刚开始对Java正则表达式中的组的概念不清晰,导致理解困难。当将“组”的概念与“子表达式”对应起来之后,理解matcher的group,start,end就完全没有障碍了