I don\'t 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\"
<
You need to use a constant of java.util.regex.Pattern for avoid recompiled the expression every time:
private static final Pattern REGEX_PATTERN =
Pattern.compile(" {2,}");
public static void main(String[] args) {
String input = "Some text with spaces";
System.out.println(
REGEX_PATTERN.matcher(input).replaceFirst(" ")
); // prints "Some text with spaces"
}
In another way, the Apache Commons Lang include in the class StringUtils the method normalizeSpace.
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.)
String a = "Some text with spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
For Java (not javascript, not php, not anyother):
txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")