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.
The reason why it’s not working: You need four backslashes in a Java string to create a single “real” backslash.
should work. But this is not the right way to do it. You don’t need a
forloop at all:and you’re done.
Explanation:
[%&_]matches any of the three characters you want to replace$0is 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
would become
which you would not want to happen. Could this be a problem?