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:
" " 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With