我正在阅读Boundary Matcher来自 Oracle 文档。我理解大部分内容,但我无法掌握 \b
边界匹配器。这是文档中的示例。
To check if a pattern begins and ends on a word boundary (as opposed to a substring within a longer string), just use \b on either side; for example, \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. To match the expression on a non-word boundary, use \B instead:
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 的工作原理。有人可以帮我描述它的用法并帮助我理解这个例子。
谢谢
最佳答案
\b
就是您所说的“ anchor ”:它将匹配输入文本中的位置。
更具体地说,\b
将匹配输入文本中的每个位置,其中:
- 没有前面的字符,后面的字符是单词字符(任何字母或数字,或下划线);
- 后面没有字符且前面的字符是单词字符;
- 前面的字符是单词字符,后面的字符不是;或
- 后面的字符是单词字符,前面的字符不是。
例如,正则表达式 dog\b
文中"my dog eats"
将匹配紧随 g
之后的位置的dog
(这是一个单词字符)和后面的空格(不是)之前。
请注意,与所有 anchor 一样,它与位置匹配这一事实意味着它不消耗任何输入文本。
其他 anchor 是 ^
, $
,环顾四周。
关于java - Java中\b边界匹配器的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21695670/