Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove escape characters from a string in JAVA

Tags:

java

regex

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 i.e., "\\\\{.*?\\\\}".

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

like image 908
MIM Avatar asked Sep 14 '12 10:09

MIM


People also ask

How do I remove all characters from a string escape?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).

How do I ignore an escape character in a string?

An escape sequence is a set of characters used in string literals that have a special meaning, such as a new line, a new page, or a tab. For example, the escape sequence \n represents a new line character. To ignore an escape sequence in your search, prepend a backslash character to the escape sequence.


1 Answers

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("\\{", "{");
like image 137
assylias Avatar answered Sep 17 '22 12:09

assylias