在Java中使用\ G边界匹配器

Mac*_*rse 4 java regex

我一直在用java学习正则表达式.我想知道在使用java的matcher时使用\ G是否有意义.我找不到任何与G一起使用的例子:(:

做这样的事情与使用\ G不会有相同的输出?

String a = "Pruebaprueba";
Matcher matcher = Pattern.compile("(\\w)").matcher(a);
while ( matcher.find() ) {
    // Do something with each letter
}
Run Code Online (Sandbox Code Playgroud)

谢谢阅读!

Nom*_*meN 7

直接来自http://java.sun.com/docs/books/tutorial/essential/regex/index.html

要求匹配仅在上一个匹配结束时发生,请使用\ 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.
Run Code Online (Sandbox Code Playgroud)

这里第二个例子只找到一个匹配,因为第二次出现的"dog"不会在上一个匹配结束时开始.

所以不,它与你的例子完全不同.我确实认为如果你将正则表达式改为"(.)"你会得到与"\ G"相同的效果.在这个人为的例子中.但是"(\ w)"会继续搜索空格,而"\ G\w"会在那时失败.