Java - regular expression to match a backslash followed by a quote

If you don't need any of regex mechanisms like predefined character classes \d, quantifiers etc. instead of replaceAll which expects regex use replace which expects literals

str = str.replace("\\\"","\"");

Both methods will replace all occurrences of targets, but replace will treat targets literally.


BUT if you really must use regex you are looking for

str = str.replaceAll("\\\\\"", "\"")

\ is special character in regex (used for instance to create \d - character class representing digits). To make regex treat \ as normal character you need to place another \ before it to turn off its special meaning (you need to escape it). So regex which we are trying to create is \\.

But to create string representing \\ so you could pass it to regex engine you need to write it as four \ ("\\\\"), because \ is also special character in String (it can be used for instance as \t to represent tabulator) so you also need to escape both \ there.

In other words you need to escape \ twice:

  • once in regex \\
  • and once in String "\\\\"

You don't need a regular expression.

str.replace("\\\"", "\"")

should work just fine.

The replace method takes two substrings and replaces all non-overlapping occurrences of the first with the second. Per the javadoc:

public String replace(CharSequence target,
                      CharSequence replacement)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

Tags:

Java

Regex