我从这个link看到这两个边界匹配非常相似:
\G
和^
。
我还看到了他们在同一link末尾显示的\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之间的细微差别是什么?
答案 0 :(得分:2)
这解释了\ G
https://forums.oracle.com/thread/1255361
\ G从字符串的开头开始搜索,并在第一个匹配结束后继续搜索。
如果在搜索开头找到匹配项,^将只提供一个搜索结果
答案 1 :(得分:1)
如javadocs中描述的那样:
\ G - 上一场比赛结束
^ - 一行的开头
使用dog
和dogdog
来尝试dogdogdog
,\G
,\^
等句子。 \G
会在不同位置找到狗的匹配,而^
只会找到第一个匹配。
至于您查询^
和\G
与句子dog dog
相似的原因。这是因为\G
的第一个匹配将来自索引0 to 3
,第二个匹配将从索引3
开始,这是<space>dog
而不是dog
因此第二场比赛失败。