How to remove escape characters from a string in JAVA

I have an input line like "\\{\\{\\{testing}}}", and I want to delete everything "\". Required o / p: "{{{testing}}}".

I am using the following code to execute this.

protected String removeEscapeChars(String regex, String remainingValue) {
    Matcher matcher = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(remainingValue);
    while (matcher.find()) {
        String before = remainingValue.substring(0, matcher.start());
        String after = remainingValue.substring(matcher.start() + 1);
        remainingValue = (before + after);
    }
    return remainingValue;
}

I pass regex like "\\\\{.*?\\\\}".

The code works fine only for the first appearance of "\ {", but not for all its occurrences. View the following outputs for different inputs.

  • i / p: "\\{testing}"- o / p:"{testing}"
  • i / p: "\\{\\{testing}}"- o / p:"{\\{testing}}"
  • i / p: "\\{\\{\\{testing}}}"- o / p:"{\\{\\{testing}}}"

I want to "\"have i / p removed from the passed string, and everything "\\{"should be replaced with "{".

I feel the problem is with the regex value, i.e. "\\\\{.*?\\\\}".

Can someone tell me what should be the value of the regex to get the required o / p.

+5
source
4

, String#replace?

String noSlashes = input.replace("\\", "");

, , :

String noSlashes = input.replace("\\{", "{");
+9

, :

String result = remainingValue.replace("\\", "");
+1

, \ {, -

String noSlashes = input.replace("\\{", "{");

, - , . , \ , {, {, }, : . {} .

+1

RegEx: "\\&([^;]{6})"

private String removeEscapeChars(String remainingValue) {
        Matcher matcher = Pattern.compile("\\&([^;]{6})", Pattern.CASE_INSENSITIVE).matcher(remainingValue);
        while (matcher.find()) {
            String before = remainingValue.substring(0, matcher.start());
            String after = remainingValue.substring(matcher.start() + 1);
            remainingValue = (before + after);
        }
        return remainingValue;
    }

.

0
source

All Articles