java正则表达式 match find匹配位置

               

如题,对于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之后,下一次匹配的位置,会在去掉开头匹配的字符串之后。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43747091/article/details/86141191