14

I've a csv string like

"abc, java, stackoverflow  ,     stack exchange   , test"

Can I use regex to remove the space around the commas to get a string like

"abc,java,stackoverflow,stack exchange,test"
3
  • 1
    What about a , "b , b" , c? Commented Jun 8, 2011 at 12:43
  • Unfortunately "b , b" will be treated as two different values, but i'm fine with that :) Commented Jun 8, 2011 at 12:46
  • okay, then Chris' solution will do. Commented Jun 8, 2011 at 12:47

1 Answer 1

29
str = str.replaceAll("\\s*,\\s*", ",");
Sign up to request clarification or add additional context in comments.

5 Comments

@Rnet: \s (which has to be written as \\s in a Java string literal) matches one whitespace character. * matches zero or more of the "thing" before it. So, \s* means zero or more whitespace characters. You can figure out the rest. ;-)
@Chris Jester-Young: Thank you:)
+1 Damn. I was thinking why replace() is not working. Now I see from the docs, that replaceAll() supports regex. Thanks!
@asgs: if you had used replace() to replace the white space, it would have replaced the space between the values also.
@Rnet actually, i was using the same regex inside the replace().

Your Answer

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.