Java Regex – 减少字符串中的空格
我没有时间去理解正则表达式,我需要快速回答。 平台是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
方法。