在正则表达式中\ \ G和^之间的区别

时间:2013-07-11 07:54:03

标签: java regex string

我从这个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之间的细微差别是什么?

2 个答案:

答案 0 :(得分:2)

这解释了\ G

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

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

如果在搜索开头找到匹配项

^将只提供一个搜索结果

答案 1 :(得分:1)

如javadocs中描述的那样:

  

\ G - 上一场比赛结束

     

^ - 一行的开头

使用dogdogdog来尝试dogdogdog\G\^等句子。 \G会在不同位置找到狗的匹配,而^只会找到第一个匹配。

至于您查询^\G与句子dog dog相似的原因。这是因为\G的第一个匹配将来自索引0 to 3,第二个匹配将从索引3开始,这是<space>dog而不是dog因此第二场比赛失败。

相关问题