更新时间:2022-12-28 15:37:59
试试这个:
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