如题。对于 java 正則表達式这几个方法匹配一次后的,匹配位置搞不太清楚,就写了几个样例。例如以下:
- String ss="ooaaoo";
- Pattern pt=Pattern.compile("(o+)");
- Matcher mt=pt.matcher(ss);
- // mt.lookingAt();
- // mt.matches();
- while(mt.find()){
- System.out.println(mt.group(1)+"|||"+mt.start());
- }
这个结果非常明显会匹配二次,一次在 0 位置,一次在 4 位置。
看以下的代码
- String ss="ooaaoo";
- Pattern pt=Pattern.compile("(o+)");
- Matcher mt=pt.matcher(ss);
- mt.lookingAt();
- // mt.matches();
- while(mt.find()){
- System.out.println(mt.group(1)+"|||"+mt.start());
- }
当我们把 matches 或 lookingat 方法之中的一个的凝视拿掉之后,仅仅会发生一次匹配,就是在 4 位置。
再看以下的代码:
- String ss="aaooaaoo";
- Pattern pt=Pattern.compile("(o+)");
- Matcher mt=pt.matcher(ss);
- mt.lookingAt();
- // mt.matches();
- while(mt.find()){
- System.out.println(mt.group(1)+"|||"+mt.start());
- }
我们的输入字符串 ss 发生了变化。
这个程序结果会发生二次匹配,一次在 2 位置,一次在 4 位置。
所以可得出下面结论:
1. 当我们的输入字符串 ss 开头不匹配正則表達式的时候,matches 和 lookingat 都不影响下次匹配位置。
2. 假设输入字符串开头匹配正則表達式。调用 matches 或 lookingat 之后。下一次匹配的位置。会在去掉开头匹配的字符串之后。
来源: http://www.bubuko.com/infodetail-2036700.html