tags:

views:

80

answers:

1

Hi: I've been learning regex with java. I wanted to know if it makes sense to use \G while using java's matcher. I couldn't find any example of \G used with java :(

Doing something like this would not have the same output as using \G?

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

Thanks for reading!

+2  A: 

Directly from http://java.sun.com/docs/books/tutorial/essential/regex/index.html

To require the match to occur only at the end of the previous match, use \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.

Here the second example finds only one match, because the second occurrence of "dog" does not start at the end of the previous match.

So no, it would not do exactly the same as your example. I do think if you'd change the regex to "(.)" you'd get the same effect as "\G." in this contrived example. But "(\w)" would go on searching after a whitespace while "\G\w" would fail at that point.

NomeN
Thanks for your reply! I also found this link interesting for a better understanding of \G:http://www.rhinocerus.net/forum/lang-perl-misc/589432-faq-6-20-what-good-g-regular-expression.html
Macarse