系列中的上一篇
当前教程
边界
系列中的下一篇

系列中的上一篇: 捕获组

系列中的下一篇: 模式类

边界

 

量词

到目前为止,我们只关心在特定输入字符串中的某个位置是否找到了匹配项。我们从不在乎匹配项在字符串中的哪个位置。

您可以通过使用边界匹配器指定此类信息来使模式匹配更精确。例如,您可能希望找到一个特定的单词,但前提是它出现在行的开头或结尾。或者您可能想知道匹配项是否发生在单词边界上,或者发生在先前匹配项的结尾。

下表列出了所有边界匹配器并对其进行了说明。

 

边界构造 描述
^ ^
$ 行的开头
$ 行的结尾
\b 单词边界
\B 非单词边界
\A 输入的开头
\G 先前匹配项的结尾
\Z 输入的结尾,但对于最终终止符(如果有)除外

\z

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.

输入的结尾

以下示例演示了边界匹配器^$的使用。如上所述,^匹配行的开头,$匹配结尾。

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.

第一个示例成功,因为模式占据了整个输入字符串。第二个示例失败,因为输入字符串在开头包含额外的空格。第三个示例指定了一个表达式,该表达式允许无限的空格,然后是行末的“dog”。第四个示例要求“dog”出现在行的开头,后面跟着无限数量的单词字符。

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.

要检查模式是否以单词边界开头和结尾(而不是更长字符串中的子字符串),只需在两侧使用\b;例如,\bdog\b

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.

要将表达式匹配到非单词边界,请使用\B


在本教程中


系列中的上一篇
当前教程
边界
系列中的下一篇

系列中的上一篇: 捕获组

系列中的下一篇: 模式类