Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace regex [closed]

Tags:

java

regex

So I'm struggling with this one a little bit. When I'm pulling strings from somewhere It's decided to add spaces in between every character.

I just need a quick regex to:

  • Replace single spaces with no space
  • replace triple spaces with 1 space (since " " turns into "   " with the added spaces).

Can someone help with this regex? I know how to do this for a single / multiple spaces, but not turning x number of spaces into 1 space.

like image 783
A_Elric Avatar asked Dec 08 '25 13:12

A_Elric


2 Answers

It is a little tricky, but here is a single regex solution:

// becomes "test string"
"t e s t   s t r i n g".replaceAll("( )  | ", "$1");

Example: http://ideone.com/O6DSk

This works because if a triple space is matched, one of the spaces will be saved in capture group 1, but if a single space is matched capture group 1 is empty. When we replace the match by the contents of the group it will turn three spaces into one and remove single spaces.

like image 186
Andrew Clark Avatar answered Dec 10 '25 03:12

Andrew Clark


s = s.replaceAll("\\s{3}", " ");  // Replace 3 spaces with one.

I assume you know to figure out, replacing single space with no space.

  • {n} matches exactly n spaces.
  • {0,n} matches 0 to n spaces.
  • {4,} matches 4 or more spaces.

To replace both single space with no space and 3 spaces with 1 space, you can use the below regex: -

s = "He llo   World";
s = s.replaceAll("(\\S)\\s{1}(\\S)", "$1$2").replaceAll("\\s{3}", " ");

System.out.println(s);

Ouput: -

Hello World

Order matters here. Because, 3 spaces will be converted to single space with the 2nd regex. If we use it before the 1st one, then eventually it will be replaced by no-space.

(\\S)\\s{1}(\\S) -> \\S is to ensure that only single space is replaced. \\S represents non-space character. If you don't have it, it will replace all the space character with no-space.

like image 45
Rohit Jain Avatar answered Dec 10 '25 04:12

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!