我没有时间了解正则表达式,我需要快速回答。平台就是Java。
我需要字符串
"Some text with spaces"
...转换为
"Some text with spaces"
即,将2个或更多连续的空格改为1个空格。
答案 0 :(得分:47)
String a = "Some text with spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
答案 1 :(得分:12)
如果我们专门谈论空间,你想要专门测试空间:
MyString = MyString.replaceAll(" +", " ");
使用 \s
会导致所有空白被替换 - 有时需要,有时则不会。
另外,只匹配2个或更多的简单方法是:
MyString = MyString.replaceAll(" {2,}", " ");
(当然,如果希望用单个空格替换任何空格,这两个示例都可以使用\s
。)
答案 2 :(得分:1)
对于Java(不是javascript,不是php,不是任何其他):
txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")
答案 3 :(得分:-1)
您需要使用常量java.util.regex.Pattern
,以避免每次重新编译表达式:
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"
}
另一方面,Apache Commons Lang在StringUtils
课程中包含方法normalizeSpace
。