1

If I write this in Scala:

System.err println "Done".replaceAll(".*$", "$0xyz")

Then the output is unexpectedly not Donexyz but Donexyzxyz.

I have some idea of what's going on – Done is being turned into Donexyz, and then a second replacement is happening, matching against Donexyz and turning it into Donexyzxyz. (Using replaceFirst produces Donexyz, confirming this.) But that doesn't explain everything -- in particular I don't know why we don't get

Done -> Donexyz -> Donexyzxyz -> Donexyzxyzxyz ->  ...

Any illumination would be appreciated.

Mohan
  • 7,302
  • 5
  • 32
  • 55
  • You need `^.+$` or `^.*$`, the pattern you have finds 2 matches in the string. – Wiktor Stribiżew Nov 11 '16 at 11:28
  • But why 2 rather than, say, 5 (`Done$`, `one$`, etc.)? – Mohan Nov 11 '16 at 11:30
  • It must be related to how matching is performed internally to find the substrings to replace. It is a common issue in many regex flavors. Here is a [related issue in C++](http://stackoverflow.com/questions/33795759/c-mac-os-x-regex-causes-infinite-loop-with-regex-replace/33799633#33799633). The point is that you should not be using a regex matching an empty string in a regex replace method unless you know what you are doing. Or use the anchors as I suggested in the first comment. See [Scala demo](http://ideone.com/TWEK8i). – Wiktor Stribiżew Nov 11 '16 at 11:45

0 Answers0