north.mister
north.mister

Reputation: 510

replaceAll not working as expected on a String

I have this line of code: temp5.replaceAll("\\W", "");

The contents of temp5 at this point are: [1, 2, 3, 4] but the regex doesn't remove anything. And when I do a toCharArray() I end up with this: [[, 1, ,, , 2, ,, , 3, ,, , 4, ]]

Am I not using the regex correctly? I was under the impression that \W should remove all punctuation and white space.

Note: temp5 is a String

And I just tested using \w, \W, and various others. Same output for all of them

Upvotes: 2

Views: 92

Answers (2)

WSDL
WSDL

Reputation: 35

    String temp5="1, 2, 3, 4";

    temp5=temp5.replaceAll("\\W", "");

    System.out.println(temp5.toCharArray());

This will help

Upvotes: 0

Jason C
Jason C

Reputation: 40336

Strings are immutable. replaceAll() returns the string with the changes made, it does not modify temp5. So you might do something like this instead:

temp5 = temp5.replaceAll("\\W", "");

After that, temp5 will be "1234".

Upvotes: 4

Related Questions