Escape special characters in the text when the text is either enclosed in double quotes or not

I am writing a regex to avoid a few special characters, including a double quote from the input.

input can be enclosed in double quotes and they must not be escaped.

Ex input:

"te(st", te(st, te"st 

expected outputs:

"te\(st", te\(st, te\"st

Used code:

String regex = "^\".*\"$";
    String value = "\"strin'g\"";
    Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[()'"\\[\\]*]");

    if (Pattern.matches(regex, value)){
        String val = value.substring(1, value.length() -1);
        String replaceAll = SPECIAL_REGEX_CHARS.matcher(val).replaceAll("\\\\$0");
        replaceAll = "\""+replaceAll+"\"";
        System.out.println(replaceAll);
    }else {
        String replaceAll = SPECIAL_REGEX_CHARS.matcher(value).replaceAll("\\\\$0");
        System.out.println(replaceAll);
    }

1 - check if the text is enclosed in double quotes. if so, avoid special characters in the text enclosed in double quotes.

2 - else. Highlight special characters in the text.

any regex expression that can combine # 1 and # 2?

Regards, Anil

+4
source share
2 answers

A simple solution with regex expression alone

if (s.startsWith("\"") && s.endsWith("\"")), , , ", , " replaceAll("^\"|\"$", ""), escaping regex, " . , .

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());

IDEONE

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());

IDEONE

:

0

lookbehind lookahead:

System.out.println(value.replaceAll("([()'\\[\\]*]|(?<!^)\"(?!$))", "\\\\$0"));

: - [()'\[\]*] ", .

, , . , , :

.replaceAll("^\".*[^\"]$", "\\\\$0")
.replaceAll("(^[^\"].*)(\"$)", "$1\\\\$2")
0

Source: https://habr.com/ru/post/1628806/


All Articles