Java关于正则表达式的类:Matcher提供了三个方法来根据正则表达式匹配字符串,他们分别是find,lookingAt和matches。
根据Matcher (Java Platform SE 7 )可以看到这两个函数的定义和说明:
boolean | find() Attempts to find the next subsequence of the input sequence that matches the pattern. |
boolean | find(int start) Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index. |
boolean | matches() Attempts to match the entire region against the pattern. |
boolean | lookingAt() Attempts to match the input sequence, starting at the beginning of the region, against the pattern. |
根据手册可以发现主要提供用于正则表达式计算的接口有三个:find,lookingAt和matches。
根据三者的定义可以大概了解三者的区别,这里以一个示例代码作为演示如下:
通过代码运行的结果,可以总结如下:
find方法:从开头或者指定的位置开始,只要找到匹配的子字符串就可以了。
lookingAt方法:必须从开头的位置开始而且开头的位置就匹配指定的字符串。
matches方法: 整个字符串匹配指定的规则。
举个例子:正则表达是是:“\\d\\d\\d\\d”
输入的字符串是:"goodbye 2022 and welcome 2023"
那么:find方法就可以匹配到,因为里面有符合正则表达式的数字 2022和2023
lookingAt和matches就不能匹配。
如果想要使得lookingAt匹配到,就需要修改一下,可以根据中文习惯改为:“2022你好,2023再见”,然后,lookingAt就可以匹配了,因为从开始的位置的2022 正好匹配正则表达式。
至于matches要想匹配的话,就只能将字符串改为"2022"这样的四个数字的字符串才可以匹配了,如果多输入一个数字“20222”都不会匹配,因为没有严格按照正则表达式的格式完全匹配。
在安全的预防里面有黑名单和白名单的说法,这里简单总结一下就是:matches类似于白名单,必须严格符合有效值的范围才可以匹配;而find方法则类似于黑名单,只要在黑名单的里面出现了,就匹配。