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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With