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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:24:31  来源:igfitidea点击:

Java Regex - reduce spaces in a string

javaregex

提问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 \swill 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 \sif 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.Patternfor 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 StringUtilsthe method normalizeSpace.

换句话说,Apache Commons Lang在类中包含StringUtils了方法normalizeSpace