Arthur Arthur - 2 months ago 10
Java Question

How to replace all occurences with regexp on prefix and suffix?

System.out.println(
"ISODate(\"333\")ISODate(\"333\")ISODate(\"333\")"
.replaceAll("ISODate\\(\".+\"\\)",
"ISODate(\"222\")"));


Result

ISODate("222")


How to replace all dates?

Answer

".+" is greedy, that will match a double quote and then the longest match before matching next double quote.

You can use non-greedy match:

System.out.println(
"ISODate(\"333\")ISODate(\"333\")ISODate(\"333\")"
.replaceAll("ISODate\\(\".+?\"\\)", 
    "ISODate(\"222\")"));

Or better performing negated character class:

System.out.println(
"ISODate(\"333\")ISODate(\"333\")ISODate(\"333\")"
.replaceAll("ISODate\\(\"[^\"]+\"\\)", 
    "ISODate(\"222\")"));
Comments