Possible Duplicate:
String.replaceAll() anomaly with greedy quantifiers in regex
Strange behavior in regexes
While
"a".replaceAll("a", "b")
"a".replaceAll("a+", "b")
"a".replaceAll("a+?", "b")
all return b, why does
"a".replaceAll("a*", "b")
return bb and
"a".replaceAll("a*?", "b")
return bab?
First replaces
atob, then advances the pointer past theb. Then it matches the end of string, and replaces withb. Since it matched an empty string, it advances the pointer, falls out of the string, and finishes, resulting inbb.first matches the start of string and replaces with
b. It doesn’t match theabecause?ina*?means “non-greedy” (match as little as possible). Since it matched an empty string, it advances the pointer, skippinga. Then it matches the end of string, replaces withband falls out of the string, resulting inbab. The end result is the same as if you did"a".replaceAll("", "b").