Boundary Matchers
到目前为止,我们仅对在特定 Importing 字符串 内的某个位置是否找到匹配项感兴趣。我们从不关心 match 发生在字符串 中的哪个位置。
通过使用边界匹配器指定此类信息,可以使 Pattern 匹配更加精确。例如,也许您有兴趣寻找一个特定的单词,但前提是该单词出现在行的开头或结尾。或者,也许您想知道匹配是在单词边界上还是在上一个匹配的末尾进行。
下表列出并说明了所有边界匹配器。
Boundary Construct | Description |
---|---|
^ | 行的开头 |
$ | 行尾 |
\b | 单词边界 |
\B | 非单词边界 |
\A | Importing 的开始 |
\G | 上一场 match 的结束 |
\Z | Importing 的结尾,但对于final终止符(如果有) |
\z | Importing 的结尾 |
以下示例演示了边界匹配器^
和$
的用法。如上所述,^
匹配行的开头,$
匹配行的结尾。
Enter your regex: ^dog$
Enter input string to search: dog
I found the text "dog" starting at index 0 and ending at index 3.
Enter your regex: ^dog$
Enter input string to search: dog
No match found.
Enter your regex: \s*dog$
Enter input string to search: dog
I found the text " dog" starting at index 0 and ending at index 15.
Enter your regex: ^dog\w*
Enter input string to search: dogblahblah
I found the text "dogblahblah" starting at index 0 and ending at index 11.
第一个示例成功,因为该 Pattern 占用了整个 Importing 字符串。第二个示例失败,因为 Importing 字符串 的开头包含多余的空格。第三个示例指定了一个表达式,该表达式允许无限制的空格,并在行尾添加“ dog”。第四个示例要求“ dog”出现在行的开头,后跟无限数量的单词字符。
要检查 Pattern 是否在单词边界处开始和结束(与较 Long 字符串 中的子字符串 相对),只需在任一侧使用\b
即可;例如\bdog\b
Enter your regex: \bdog\b
Enter input string to search: The dog plays in the yard.
I found the text "dog" starting at index 4 and ending at index 7.
Enter your regex: \bdog\b
Enter input string to search: The doggie plays in the yard.
No match found.
要在非单词边界上匹配表达式,请改用\B
:
Enter your regex: \bdog\B
Enter input string to search: The dog plays in the yard.
No match found.
Enter your regex: \bdog\B
Enter input string to search: The doggie plays in the yard.
I found the text "dog" starting at index 4 and ending at index 7.
要要求匹配仅在上一次匹配结束时进行,请使用\G
:
Enter your regex: dog
Enter input string to search: dog dog
I found the text "dog" starting at index 0 and ending at index 3.
I found the text "dog" starting at index 4 and ending at index 7.
Enter your regex: \Gdog
Enter input string to search: dog dog
I found the text "dog" starting at index 0 and ending at index 3.
在这里,第二个示例仅找到一个匹配项,因为第二次出现的“ dog”不是从上一个匹配项的末尾开始的。