String a = "Some text with spaces"; String b = a.replaceAll("\\s+", " "); assert b.equals("Some text with spaces");