0

Searched all over to find out how to replace quoted values in Strings. (I expected this to be a common requirement!)

Considered this simple example:

        String test1 = "This is a string with a \"dog\" and a \"cat\" that are unwanted.";
        System.out.println(test1);
        System.out.println(test1.replaceAll("\".*\"", "ZAPPED"));

produces:

This is a string with a "dog" and a "cat" that are unwanted.
This is a string with a ZAPPED that are unwanted.

But I wanted:

This is a string with a ZAPPED and a ZAPPED that are unwanted.

I expected the pattern matching to stop at the second quote (at least in replaceAll()).

  • Use `.*?` instead of `.*` `test1.replaceAll("\".*?\"", "ZAPPED")` Using `.*` is a greedy capture due to which it captures all characters and captures all text in between two doublequotes. – Pushpesh Kumar Rajwanshi Feb 05 '19 at 16:26
  • Possible duplicate of [How can I fix my regex to not match too much with a greedy quantifier?](https://stackoverflow.com/questions/255815/how-can-i-fix-my-regex-to-not-match-too-much-with-a-greedy-quantifier) – Pushpesh Kumar Rajwanshi Feb 05 '19 at 16:27
  • 1
    Ah! Of course - just too simple! Thank you! – Jon Kemp Feb 05 '19 at 17:09

0 Answers0