views:

1458

answers:

2

I dont have time to get my head around regex and I need a quick answer. Platform is Java

I need the String "Some text   with spaces" to be converted to "Some text with spaces" e.g. 2 spaces to be change to 1 in a String

+17  A: 
String a = "Some    text  with   spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
Tim Jansen
This will make replacements of all single spaces with a single space, not very efficient. You should only replace if there are two or more consecutively.
Chris Ballance
@Chris - don't start optimizing the regex prematurely, I believe this will suffice.
Yuval A
Yes, this solution is not as efficient as it could be, but that would only matter if this operation were taking place inside a performance hotspot. It's definitely not worth a downvote.
Alan Moore
There's nothing optimized about not replacing single spaces with single spaces. This *guarantees* a string replacement for every word boundary in your string.
Chris Ballance
It's a valid point, and I would always use \s{2,} or equivalent in this situation, but practically speaking, it's just not that important.
Alan Moore
I wouldn't be surprised if this is optimized by the libraries already to only do replacements on multiple spaces. This is readable and gets the job done.
Rontologist
+4  A: 

If we're talking specifically about spaces, you want to be testing specifically for spaces:

MyString = MyString.replaceAll(" +", " ");

Using \s will result in all whitespace being replaced - sometimes desired, othertimes not.

Also, a simpler way to only match 2 or more is:

MyString = MyString.replaceAll(" {2,}", " ");

(Of course, both of these examples can use \s if any whitespace is desired to be replaced with a single space.)

Peter Boughton
It worth remembering that you need something like myString = myString.replaceAll(" +", " "); otherwise it won't do anything useful.
Peter Lawrey
Indeed - I think I simply copied the format of a (now deleted) answer, but will correct it.
Peter Boughton