Why does ".*" and ".+" give different results?
System.out.println("foo".replaceAll(".+", "bar")); // --> "bar"
System.out.println("foo".replaceAll(".*", "bar")); //--> "barbar"
I would expect "bar" for both, since * and + are both greedy and should match the whole String. (The above example is Java, but other Tools, like http://www.gskinner.com/RegExr/ give me the same result)
You're right about both being greedy but ".*"
is matching two strings: the first one is "foo"
and the second is ""
. ".+"
will only match "foo"
.
Both try to match the longest possible string which is "foo"
. After that, they try to find the longest matching string coming after the previous match. In this phase, ".*"
is able to match an empty string while ".+"
won't.
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