在 Java 中寻找快速、简单的方法来更改此字符串
" hello there "
看起来像这样的东西
"hello there"
我用一个空格替换所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
这样的事情让我部分地在那里
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但不完全是。
最佳答案
试试这个:
String after = before.trim().replaceAll(" +", " ");
另见
-
String.trim()
- 返回字符串的副本,省略前导和尾随空格。
- regular-expressions.info/Repetition
没有 trim()
正则表达式
也可以只用一个 replaceAll
来做到这一点,但这比 trim()
解决方案的可读性差得多。尽管如此,这里提供它只是为了展示正则表达式可以做什么:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
有 3 个备选:
^_+
: 字符串开头的任意空格序列- 用
$1
匹配替换,捕获空字符串
- 用
_+$
: 字符串末尾的任意空格序列- 用
$1
匹配替换,捕获空字符串
- 用
(_)+
:任何与上述都不匹配的空格序列,这意味着它在中间- 用
$1
匹配和替换,捕获一个空格
- 用
另见
关于Java如何用字符串中的单个空格替换2个或多个空格并删除前导和尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2932392/