Search code examples
javastringreplacereplaceall

Pattern Replacing in string with escaped characters failing with replaceAll


I have a use case where I want to replace some values in html string, so I need to do replaceAll for that, but that is not working, although replace is working fine, here is my code:

    String str  = "<style type=\"text/css\">#include(\"Invoice_Service_Tax.css\")</style>";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));

output is :

<style type="text/css">some-value</style>
<style type="text/css">#include("Invoice_Service_Tax.css")</style>

For my use case I need to do replaceAll only, I tried with below patterns also but no help:

"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"

Solution

  • Replace doesn't look for special chars, just a literal replace while replaceAll uses regexes so there are some special characters.

    The problem with the regex is that ( is a special character for grouping so you need to escape it.

    #include\\(\"Invoice_Service_Tax.css\"\\) should work with your replaceAll