只有一个转义正则表达式的简单解决方案
您可以使用 if (s.startsWith("\"") && s.endsWith("\"")) 检查字符串是否同时包含前导和尾随 " ,如果是,则可以使用 replaceAll("^\"|\"$", "") 修剪前导和尾随 " ,然后使用转义正则表达式转义,然后再添加 " . 否则,只需要逃避你集合中的角色 .
String SPECIAL_REGEX_CHARS = "[()'\"\\[\\]*]";
String s = "\"te(st\""; // => "te\(st"
String result;
if (s.startsWith("\"") && s.endsWith("\"")) {
result = "\"" + s.replaceAll("^\"|\"$", "").replaceAll(SPECIAL_REGEX_CHARS, "\\\\$0") + "\"";
}
else {
result = s.replaceAll(SPECIAL_REGEX_CHARS, "\\\\$0");
}
System.out.println(result.toString());
使用appendReplacement“回调”的替代解决方案
以下是使用替换的一个正则表达式的方法:
String SPECIAL_REGEX_CHARS = "[()'\"\\[\\]*]";
//String s = "\"te(st\""; // => "te\(st"
//String s = "te(st"; // => te\(st
String s = "te\"st"; // => te\"st
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(?s)\"(.*)\"|(.*)").matcher(s);
if (m.matches()) {
if (m.group(1) == null) { // we have no quotes around
m.appendReplacement(result, m.group(2).replaceAll(SPECIAL_REGEX_CHARS, "\\\\\\\\$0"));
}
else {
m.appendReplacement(result, "\"" + m.group(1).replaceAll(SPECIAL_REGEX_CHARS, "\\\\\\\\$0") + "\"");
}
}
m.appendTail(result);
System.out.println(result.toString());
要点:
使用带有2个备用分支的 (?s)\"(.*)\"|(.*) 正则表达式: ".*" 匹配以 " 开头并以 " 结尾的字符串(注意 (?s) 是DOTALL内联修饰符,允许匹配字符串与换行符序列)或 .* 替代匹配所有其他字符串 .
如果第一个选项匹配,我们只需替换第一个捕获组中选定的特殊字符,然后在两端添加 " .
如果匹配第二个备选方案,只需在整个第2组中添加转义符号即可 .
要替换为文字反斜杠,您需要在替换模式中使用 \\\\\\\\ .