gtgaxiola
gtgaxiola

Reputation: 9331

Escape Backslash only if not already escaped

Very simple test:

String value = "Test escape single backslash C:\\Dir  [Should not escape \\\\characters here\\\\]";
String result = value.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));
System.out.println(value);
System.out.println(result);

I'm getting the output:

Test escape single backslash C:\Dir  [Should not escape \\characters here\\]
Test escape single backslash C:\\Dir  [Should not escape \\\\characters here\\\\]

Changing the expression to:

"(?<![\\\\])"+Pattern.quote("\\")

as in

String result = value.replaceAll("(?<![\\\\])"+Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));

Gives me:

Test escape single backslash C:\Dir  [Should not escape \\characters here\\]
Test escape single backslash C:\\Dir  [Should not escape \\\characters here\\\]

Which is close, but no cigar.

What am I missing?

The expected output:

Test escape single backslash C:\\Dir  [Should not escape \\characters here\\]

Upvotes: 3

Views: 1465

Answers (2)

Pshemo
Pshemo

Reputation: 124235

How about something like

String result = value.replaceAll("\\\\{1,2}",  Matcher.quoteReplacement("\\\\"));

Idea is to let matcher consume two \ literals and don't change them (replace them with themselves Matcher.quoteReplacement("\\\\")) but if only one \ literal will be found also replace it with two \ \ (same replacement as in first case).

Something like

\\\
^^  - replace with `\\`
  ^ - also replace with `\\`

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

Use four backslashes in regex to match a single backslash character.

String value = "Test escape single backslash C:\\Dir  [Should not escape \\\\characters here\\\\]";
System.out.println(value.replaceAll("(?<!\\\\)\\\\(?!\\\\)", "\\\\\\\\"));
  • (?<!\\\\)\\\\(?!\\\\) matches only a single back-slash character.
  • (?<!\\\\) negative lookbehind asserts that the match won't be preceeded by a backslash characeter.
  • \\\\ Matches a single backslash.
  • (?!\\\\) negative lookahead asserts that the match won't be followed by a backslash character.

Output:

Test escape single backslash C:\\Dir  [Should not escape \\characters here\\]

Upvotes: 3

Related Questions