Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why replaceFirst and replaceAll give different results?

Tags:

java

regex

The following code will set str to "testss"

String str = "test".replaceAll("(.*)$","$1s");

Where as the following code will set it to "tests"

String str = "test".replaceFirst("(.*)$","$1s");

I would have expected both operations to produce the same result. Can someone explain why replaceAll adds an extra s to the end of the string?

like image 456
Reactgular Avatar asked Oct 18 '12 05:10

Reactgular


1 Answers

This is because "(.*)$" captures two strings from "test", "test" and the empty string (""). So replaceAll will add two "s".

like image 61
Matthew Farwell Avatar answered Oct 15 '22 14:10

Matthew Farwell