Fevly Pallar
Fevly Pallar

Reputation: 3099

Replacing a special character (along with space is considered same)

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

Answers (2)

racraman
racraman

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

Braj
Braj

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

Greedy quantifiers

  • X? X, once or not at all
  • X* X, zero or more times
  • X+ X, one or more times

Upvotes: 4

Related Questions