A simple solution with regex expression alone
if (s.startsWith("\"") && s.endsWith("\"")), , , ", , " replaceAll("^\"|\"$", ""), escaping regex, " . , .
String SPECIAL_REGEX_CHARS = "[()'\"\\[\\]*]";
String s = "\"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());
IDEONE
appendReplacement " "
, :
String SPECIAL_REGEX_CHARS = "[()'\"\\[\\]*]";
String s = "te\"st";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(?s)\"(.*)\"|(.*)").matcher(s);
if (m.matches()) {
if (m.group(1) == null) {
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());
IDEONE
: