0

I'm looking to replace all occurrences of an escaped quote (\") with (\\\") in the string, then replacing all remaining unescaped quotes (") with escaped quotes (\"). Here's what I tried so far:

row = row.replaceAll("\\\\(?>\")", "\\\\\"");
row = row.replaceAll("((?<!\\\\)\")", "\"");

Example Input: "This is a test with \" and "'s where \" is replaced with triple \'s before "

Example Output: \"This is a test with \\\" and \"'s where \\\" is replaced with triple \'s before \"

\\(?>\")" works on https://www.freeformatter.com/java-regex-tester.html#ad-output in replaceAll doesn't find escaped quotes.

Any help on this is appreciated.

user3509528
  • 97
  • 10
  • @Mandy8055 Nope, that catches all \'s not just the ones that prefix quotes. So "This is a test with \ and \" ..." both \'s get replaced. – user3509528 Jun 19 '20 at 04:21

3 Answers3

0

Just replace single backslash with triple backslash, then replace quotes with backslash-quote:

row = row.replaceAll("\\\\(?!')", "\\\\\\\\\\\\").replace("\"", "\\\"");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

It looks like you need to have four \'s to find a . I used a lookback and forward to find \". Credit to java, regular expression, need to escape backslash in regex.

"\\\\(?>\")" will find \".

"(?<!\\\\)\"" will find "'s without \ before it.

So the solution I found to do both is:

        Pattern escapePattern = Pattern.compile("\\\\(?>\")");
        Pattern quotePattern = Pattern.compile("(?<!\\\\)\"");

        for(String row : rows.split("\n")) {
            Matcher escapeMatcher = escapePattern.matcher(row.trim());
            String escapedString = escapeMatcher.replaceAll("\\\\\\\\\\\\\"");

            Matcher quoteMatcher = quotePattern.matcher(escapedString);
            queryRows.add(quoteMatcher.replaceAll("\\\\\""));
        }
user3509528
  • 97
  • 10
0

first replace single ( \ ) with ( \\ ) and then replace ( " ) with ( \" )

row = row.replace("\\", "\\\\").replace("\"", "\\\"");
chitresh
  • 316
  • 4
  • 11