Reputation: 3099
Have a look at this string String str = "first,second, there";
. there are ,
and ,
( there's a space
after the second comma). How do I express it in RegEx
as .replaceAll()
's parameters so the
output would be :
"first second there"
. <-- the amount on each space
will be same.
I had tried some combinations but still fail. One of them is :
String temp2 = str.replaceAll("[\\,\\, ]", " ");
will print first second there
.
Thanks before.
Upvotes: 0
Views: 130
Reputation: 5034
String temp2 = str.replaceAll(", ?", " ");
The ? Means optional (ie zero or once), or
String temp2 = str.replaceAll(", *", " ");
Where the * means zero or more (many) spaces
Upvotes: 1
Reputation: 46841
Simply use , *
to match comma followed by zero or more spaces and replace with single space.
String str = "first,second, there";
System.out.println(str.replaceAll(", *", " "));
output:
first second there
Read more about Java Pattern
X?
X, once or not at allX*
X, zero or more timesX+
X, one or more timesUpvotes: 4