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

2
  • 9
    s = s.replaceAll("[^a-zA-Z0-9]+", "%"); Strings are immutable. Commented Jan 29, 2014 at 16:14
  • 1
    @ZouZou: omg thx! 4 secs, nice response time xD Commented Jan 29, 2014 at 16:17

4 Answers 4

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 
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not your buddy, pal.
What dude are you all talking about ? :)
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.

Comments

1

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

String newStr = s.replace(...) 

2 Comments

It's fantastic how fast problems are being solved on stackoverflow
When they are this simple...
-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.