I'm trying to replace all special characters with a "%", like:
"123.456/789" -> "123%465%798"
my regular expression is:
[^a-zA-Z0-9]+
In online tools* it works perfecly, but in java
s.replaceAll("[^a-zA-Z0-9]+", "%");
strings remain untouched.
*I tried: http://www.regexplanet.com/ http://regex101.com/ and others
Strings are immutable. You forgot to reassign new String to the s variable :)
s = s.replaceAll("[^a-zA-Z0-9]+", "%");
// ^ this creates a new String
replaceAll() like all methods in String class, DO NOT modify String on which you invoke a method. This is why we say that String is immutable object. If you want to 'modify' it, you need to do
s = s.replaceAll("[^a-zA-Z0-9]+", "%");
In fact you don't modify String s. What happens here is that new String object is returned from a function. Then you assign its reference to s.
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