Search code examples
javaregexreplaceall

regex to match double qoutes not followed by odd number of backslash


I want to replace double-quotes not followed by odd number of backslash with empty string.

For eg:

String : "hello \" world \\" , "hello \\\" world\\\\"
Regex : ?
Result : hello \" world \\ , hello \\\" world\\\\ (after replaced with empty string )

at the same time the \\ and \" are replaced by \ and "
i do that simply with regex\\ and \"

I need the regex to replace " not followed by odd number of \ . I am making a simple parser that ignores the string inside " "
so, somebody help.


Solution

  • this regex will give you the exact result it should be + instead of {0,20} but java won't allow that, So you can put double the maximum expected number of expected \ instead of 20

        String text = "\"hello \\\" world \\\\\" , \"hello \\\\\\\" world\\\\\\\\\"";
        String newText = text.replaceAll("(?<!(?<!\\\\)(\\\\)(\\\\\\\\){0,20})\"", "");
        System.out.println("newText = " + newText);