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!
A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations: The matches method attempts to match the entire input sequence against the pattern.
The regular expression token "\b" is called a word boundary. It matches at the start or the end of a word. By itself, it results in a zero-length match.
Pattern matcher() method in Java with examples The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With