2

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

Jason C
40.6k16 gold badges136 silver badges201 bronze badges
asked Mar 14, 2014 at 3:31
1
  • yes temp 5 is a string Commented Mar 14, 2014 at 3:34

2 Answers 2

4

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".

answered Mar 14, 2014 at 3:33
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my god....I am stupid....thanks a bunch (should have read the freaking API ugh)
looks like 2day, you will reach 10K :)
0
 String temp5="1, 2, 3, 4";
 temp5=temp5.replaceAll("\\W", "");
 System.out.println(temp5.toCharArray());

This will help

answered Mar 14, 2014 at 3:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.