简体   繁体   中英

How to remove escape characters from a string in JAVA

I have input string like "\\\\{\\\\{\\\\{testing}}}" and I want to remove all "\\" . Required o/p: "{{{testing}}}" .

I am using following code to accomplish 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 am passing regex as "\\\\\\\\{.*?\\\\\\\\}" .

Code is working fine only for 1st occurrence of "\\{" but not for all its occurrences. Seeing the following outputs for different inputs.

  1. i/p : "\\\\{testing}" - o/p: "{testing}"
  2. i/p : "\\\\{\\\\{testing}}" - o/p: "{\\\\{testing}}"
  3. i/p : "\\\\{\\\\{\\\\{testing}}}" - o/p: "{\\\\{\\\\{testing}}}"

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

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

Can anyone let me know what should be the regex value to the get required o/p.

Any reasons why you are not simply using String#replace ?

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

Or, if you need to remove backslashes only when they are before opening curly braces:

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

它应该像下面这样简单:

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

As it's been answered before, if you only want to remove the slashes \\ before the { , the best way is just to use

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

But in your question you asked Can anyone let me know what should be the regex value . If you are using regular expressions because you want to remove the \\ not just before any { , but only in those { that are properly closed later with } , then the answer is: NO. You can't match nested {} with regex.

Change the 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;
    }

it should work..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM