Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - Why replaceAll is not working?

Tags:

java

regex

Im starting to learn regex and I don't know if I understand it correctly.

I have a problem with function replaceAll because it does not replace the character in a string that I want to replace.

Here is my code:

public class TestingRegex {
   public static void main (String args[]) {
      String string = "Hel%l&+++o_Wor_++l%d&#";

      char specialCharacters[] = {'%', '%', '&', '_'};

      for (char sc : specialCharacters) {
          if (string.contains(sc + ""))
              string = string.replaceAll(sc + "", "\\" + sc);
      }

      System.out.println("New String: " + string);
   }
}

The output is the same as the original. Nothing changed.

I want the output to be : Hel\%l\&+++o\_Wor\_++l\%d\&\#.

Please help. Thanks in advance.

like image 866
NinjaBoy Avatar asked Jul 12 '12 07:07

NinjaBoy


1 Answers

The reason why it's not working: You need four backslashes in a Java string to create a single "real" backslash.

string = string.replaceAll(sc, "\\\\" + sc);

should work. But this is not the right way to do it. You don't need a for loop at all:

String string = "Hel%l&+++o_Wor_++l%d&#";
string = string.replaceAll("[%&_]", "\\\\$0");

and you're done.

Explanation:

  • [%&_] matches any of the three characters you want to replace
  • $0 is the result of the match, so
  • "\\\\$0" means "a backslash plus whatever was matched by the regex".

Caveat: This solution is obviously not checking whether any of those characters had already been escaped previously. So

Hello\%

would become

Hello\\%

which you would not want to happen. Could this be a problem?

like image 54
Tim Pietzcker Avatar answered Oct 22 '22 13:10

Tim Pietzcker