详解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的位置为起始位置

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

测试开发Kevin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值