Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex replace

Tags:

java

regex

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"
like image 849
Rnet Avatar asked Jun 08 '11 12:06

Rnet


People also ask

Can we use regex in replace Java?

regex package for searching and replacing matching characters or substring. Since String is immutable in Java it cannot be changed, hence this method returns a new modified String. If you want to use that String you must store it back on the relevant variable.

How do you find and replace in a regular expression in Java?

They can be used to search, edit, or manipulate text and data. The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.


1 Answers

str = str.replaceAll("\\s*,\\s*", ",");
like image 157
Chris Jester-Young Avatar answered Oct 03 '22 01:10

Chris Jester-Young