3

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

user3181103
  • 113
  • 1
  • 2
  • 5

4 Answers4

5

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
Amit Sharma
  • 5,844
  • 5
  • 25
  • 34
4

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.

MateuszPrzybyla
  • 897
  • 8
  • 17
1

You can't change a String, instead replaceAll returns a new value. so you should use it like this

String newStr = s.replace(...)
Yanis
  • 4,847
  • 2
  • 17
  • 17
-1

Working code as per your expectations :)

import java.util.regex.Pattern;


public class Regex {

    public static void main(String[] args) {
        String s = "123.456/789";
        Pattern p = Pattern.compile("[^a-zA-Z0-9]+");
        String newStr = s.replaceAll("[^a-zA-Z0-9]+", "%");
        System.out.println(s + " -> " + newStr);
    }
}

Output : 123.456/789 -> 123%456%789

Jaffar Ramay
  • 1,147
  • 8
  • 13