【发布时间】:2009-02-22 19:17:44
【问题描述】:
我没有时间了解正则表达式,我需要一个快速的答案。平台是 Java。
我需要字符串
"Some text with spaces"
...要转换成
"Some text with spaces"
即将2个或多个连续空格改为1个空格。
【问题讨论】:
-
您的意思是只有空格,还是“任何连续的空白字符”(可能包括制表符等)?
我没有时间了解正则表达式,我需要一个快速的答案。平台是 Java。
我需要字符串
"Some text with spaces"
...要转换成
"Some text with spaces"
即将2个或多个连续空格改为1个空格。
【问题讨论】:
String a = "Some text with spaces";
String b = a.replaceAll("\\s+", " ");
assert b.equals("Some text with spaces");
【讨论】:
如果我们专门讨论空间,您希望专门针对空间进行测试:
MyString = MyString.replaceAll(" +", " ");
使用 \s 将导致 所有空格 被替换 - 有时需要,有时不需要。
此外,仅匹配 2 个或更多的更简单方法是:
MyString = MyString.replaceAll(" {2,}", " ");
(当然,如果希望将任何空格替换为单个空格,这两个示例都可以使用\s。)
【讨论】:
对于 Java(不是 javascript,不是 php,不是其他):
txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")
【讨论】:
您需要使用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。
【讨论】: