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"
David Newcomb
11k3 gold badges52 silver badges63 bronze badges
asked Jun 8, 2011 at 12:40
Rnet
5,06810 gold badges54 silver badges85 bronze badges
1 Answer 1
str = str.replaceAll("\\s*,\\s*", ",");
answered Jun 8, 2011 at 12:41
C. K. Young
224k47 gold badges394 silver badges446 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
C. K. Young
@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. ;-)Rnet
@Chris Jester-Young: Thank you:)
asgs
+1 Damn. I was thinking why
replace() is not working. Now I see from the docs, that replaceAll() supports regex. Thanks!Rnet
@asgs: if you had used replace() to replace the white space, it would have replaced the space between the values also.
asgs
@Rnet actually, i was using the same regex inside the
replace().lang-java
a , "b , b" , c?