Use of whitespace in RE is a pain, but I believe they work. The OP's problem can also be solved using StringTokenizer or the split() method. However, to use RE (uncomment the println() to view how the matcher is breaking up the String), here is a sample code:
import java.util.regex.*;
public class Two21WS {
private String str = "";
private Pattern pattern = Pattern.compile ("\\s{2,}"); // multiple spaces
public Two21WS (String s) {
StringBuffer sb = new StringBuffer();
Matcher matcher = pattern.matcher (s);
int startNext = 0;
while (matcher.find (startNext)) {
if (startNext == 0)
sb.append (s.substring (0, matcher.start()));
else
sb.append (s.substring (startNext, matcher.start()));
sb.append (" ");
startNext = matcher.end();
//System.out.println ("Start, end = " + matcher.start()+", "+matcher.end() +
// ", sb: \"" + sb.toString() + "\"");
}
sb.append (s.substring (startNext));
str = sb.toString();
}
public String toString () {
return str;
}
public static void main (String[] args) {
String tester = " a b cdef gh ij kl";
System.out.println ("Initial: \"" + tester + "\"");
System.out.println ("Two21WS: \"" + new Two21WS(tester) + "\"");
}}
It produces the following (compile with javac and run at the command prompt):
% java Two21WS Initial: " a b cdef gh ij kl" Two21WS: " a b cdef gh ij kl"