您的位置 首页 java

详解java正则中的find

Java 中使用正则时,我们经常会用到 find 和matches方法,二者的区别如下:

  • find()方法在部分匹配时和完全匹配时返回true,匹配不上返回false;
  • matches()方法只有在完全匹配时返回true,匹配不上和部分匹配都返回false。

我在一次偶然的机会,发现了一个有趣的现象,代码如下:

    String line = "aaab";  
    String  Pattern  = "a*b";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(line);
    System.out.println(m.find());
    System.out.println(m.find());   

运行代码后发现结果是

true

false
对于第一个结果true 没有任何异议,而第二个结果中为何是false呢?百思不得其解之后,我还是老老实实地看了官方对于函数的说明,重点加黑,直接翻译就是:如果找到了结果,然后没有进行reset, 下一次的find将不匹配之前找到的结果(本人英语水平有限,这里完全是猜的)

/**

* Attempts to find the next subsequence of the input sequence that matches

* the pattern.

*

* <p> This method starts at the beginning of this matcher’s region, or, if

* a previous invocation of the method was successful and the matcher has

* not since been reset, at the first character not matched by the previous

* match.

*

* <p> If the match succeeds then more information can be obtained via the

* <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>

*

* @return <tt>true</tt> if, and only if, a subsequence of the input

* sequence matches this matcher’s pattern

*/

为了验证自己的猜测,我写了如下代码

     String line = "aaabab";//更改了需要匹配规则的字符,确保可以找find到两次规则a*b
    String pattern = "a*b";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(line);
    System.out.println(m.find());     
    System.out.println(m.end());//验证第一次匹配结束的位置
    System.out.println(m.find());
    System.out.println(m.start());//验证第二次匹配开始的位置
    m.reset();
    System.out.println(m.find()); //验证由于进行了reset,第三次find重新开始  

运行结果如下:
true

4

true

4

true

通过运行结果可以证明我猜测翻译的内容是正确的,即:

1.如果连续调用find方法,后面的find会从前面匹配到的位置继续开始find,而不是从头开始匹配;

2.通过reset 会设置find的位置为起始位置

文章来源:智云一二三科技

文章标题:详解java正则中的find

文章地址:https://www.zhihuclub.com/197658.shtml

关于作者: 智云科技

热门文章

网站地图