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
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
String a = "Some text with spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
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.)