Java Regex - 减少字符串中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/575500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Regex - reduce spaces in a string
提问by
I don't have time to get my head around regex and I need a quick answer. Platform is Java.
我没有时间去了解正则表达式,我需要一个快速的答案。平台是Java。
I need the string
我需要字符串
"Some text with spaces"
...to be converted to
...要转换为
"Some text with spaces"
i.e., 2 or more consecutive spaces to be changed to 1 space.
即,2 个或更多连续空格要更改为 1 个空格。
回答by Tim Jansen
String a = "Some text with spaces";
String b = a.replaceAll("\s+", " ");
assert b.equals("Some text with spaces");
回答by Peter Boughton
If we're talking specifically about spaces, you want to be testing specifically for spaces:
如果我们专门讨论空间,您希望专门针对空间进行测试:
MyString = MyString.replaceAll(" +", " ");
Using \s
will result in all whitespacebeing replaced - sometimes desired, othertimes not.
使用\s
将导致所有空格被替换 - 有时需要,有时不需要。
Also, a simpler way to only match 2 or more is:
此外,仅匹配 2 个或更多的更简单方法是:
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.)
(当然,\s
如果希望将任何空格替换为单个空格,则这两个示例都可以使用。)
回答by surfealokesea
For Java (not javascript, not php, not anyother):
对于 Java(不是 javascript,不是 php,不是任何其他):
txt.replaceAll("\p{javaSpaceChar}{2,}"," ")
回答by Paul Vargas
You need to use a constant of java.util.regex.Pattern
for avoid recompiled the expression every time:
您需要使用一个常量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"
}
In another way, the Apache Commons Langinclude in the class StringUtils
the method normalizeSpace
.
换句话说,Apache Commons Lang在类中包含StringUtils
了方法normalizeSpace
。