Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replaceAll() regex does not work [duplicate]

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

like image 947
user3181103 Avatar asked Feb 08 '26 01:02

user3181103


2 Answers

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
like image 118
Amit Sharma Avatar answered Feb 09 '26 16:02

Amit Sharma


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.

like image 37
MateuszPrzybyla Avatar answered Feb 09 '26 16:02

MateuszPrzybyla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!