非常简单的测试:
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);
我得到了输出:
Test escape single backslash C:\Dir [Should not escape \\characters here\\]
Test escape single backslash C:\\Dir [Should not escape \\\\characters here\\\\]
将表达式更改为:
"(?<![\\\\])"+Pattern.quote("\\")
,如
String result = value.replaceAll("(?<![\\\\])"+Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"));
给我:
Test escape single backslash C:\Dir [Should not escape \\characters here\\]
Test escape single backslash C:\\Dir [Should not escape \\\characters here\\\]
哪个很近,但没有雪茄。
我错过了什么?
预期产出:
Test escape single backslash C:\\Dir [Should not escape \\characters here\\]
答案 0 :(得分:3)
在正则表达式中使用四个反斜杠来匹配单个反斜杠字符。
String value = "Test escape single backslash C:\\Dir [Should not escape \\\\characters here\\\\]";
System.out.println(value.replaceAll("(?<!\\\\)\\\\(?!\\\\)", "\\\\\\\\"));
(?<!\\\\)\\\\(?!\\\\)
只匹配一个反斜杠字符。(?<!\\\\)
负面后卫声称匹配不会出现反斜杠追踪者。\\\\
匹配单个反斜杠。(?!\\\\)
否定前瞻声明匹配后面不会出现反斜杠字符。输出:
Test escape single backslash C:\\Dir [Should not escape \\characters here\\]
答案 1 :(得分:2)
像
这样的东西String result = value.replaceAll("\\\\{1,2}", Matcher.quoteReplacement("\\\\"));
想法是让匹配器使用两个\
文字并且不要更改它们(用自己Matcher.quoteReplacement("\\\\")
替换它们)但是如果只找到一个\
文字也会替换它们它有两个\
\
(与第一种情况相同的替换)。
像
这样的东西\\\
^^ - replace with `\\`
^ - also replace with `\\`