更新时间:2022-12-28 16:00:26
试试这个:
String after = before.trim().replaceAll(" +", " ");
String.trim()
也可以只用一个 replaceAll
来做到这一点,但这比 trim()
解决方案可读性要差得多.尽管如此,这里提供它只是为了展示正则表达式可以做什么:
It's also possible to do this with just one replaceAll
, but this is much less readable than the trim()
solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
有 3 个备选:
^_+
: 字符串开头的任意空格序列$1
,捕获空字符串^_+
: any sequence of spaces at the beginning of the string
$1
, which captures the empty string$1
,捕获空字符串$1
, which captures the empty string$1
,捕获一个空格$1
, which captures a single space