我们之前的学习中,匹配是发生在输入字符串任意位置的,但是某些场景下,我们需要某些匹配仅仅对输入字符串的开始或者结尾处进行匹配,这就引入Boundary Matcher概念。
通过约定特殊的语法格式来满足特定意义,在Java API中定义了如下的Boundray Construct.
Boundary Construct | Description |
---|---|
^ | The beginning of a line |
$ | The end of a line |
\b | A word boundary |
\B | A non-word boundary |
\A | The beginning of the input |
\G | The end of the previous match |
\Z | The end of the input but for the final terminator, if any |
\z | The end of the input |
下面通过几个示例来感受一下:
这里对\G
进行一个补充说明,上面的解释”The end of the previous match”字面的意思是:”上一次匹配的结尾”,给人的感觉一头雾水,通过下面的例子进一步了解一下:
这里为什么第二个dog
不能匹配到?原因在于我们的正则表达式说明只有紧接着上一次的匹配的字符后面匹配,现在两个dog
字符串中间有空格,所以后面的dog就不匹配了,接下来的示例可以进一步验证这个: