在正则表达式中,\\G和^有什么区别?

4
我从这个链接中了解到,这两个区限匹配有些相似:\G^
我也看过同一个链接末尾提供的\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.

与没有边界匹配器相比,这非常清晰明了,但是对于以下情况:

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.

vs

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.

这两者之间有什么微妙的区别?

2个回答

4

这里讲解了\G的相关内容。

https://forums.oracle.com/thread/1255361

\G从字符串的开头开始搜索,并在第一个匹配结束后继续搜索。

^只会返回一个结果,因为如果匹配项在搜索开始处被发现,搜索就会结束。


很抱歉,链接https://forums.oracle.com/thread/1255361已损坏。 - HolyLance

3

正如 javadoc 中所描述的:

\G - 上一次匹配的结尾

^ - 一行的开头

尝试使用 \G\^ 对像 dogdogdogdogdogdog 等句子进行匹配。当 dog 处于不同位置时,\G 可以找到匹配项,而 ^ 只会找到第一个。

至于你为什么要查询在句子 dog dog^\G 为什么相似。这是因为 \G 的第一次匹配将从索引 0 到 3 开始,第二次匹配将从索引 3 开始,即 <space>dog 而不是 dog,因此第二次匹配失败。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接