Java如何用字符串中的单个空格替换2个或更多空格并删除前导和尾随空格 [英] Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces
本文介绍了Java如何用字符串中的单个空格替换2个或更多空格并删除前导和尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中寻找快速,简单的方法来更改此字符串
Looking for quick, simple way in Java to change this string
" hello there "
看起来像这样的东西
"hello there"
我用一个空格替换所有这些多个空格,除了我也希望字符串开头的一个或多个空格消失。
where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.
这样的东西让我部分地在那里
Something like this gets me partly there
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但不完全。
推荐答案
试试这个:
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 thetrim()
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- Match and replace with
$1
, which captures the empty string
- 匹配和替换为
$ 1
,它捕获空字符串
- Match and replace with
$1
, which captures the empty string
- 匹配和替换使用
$ 1
,捕获单个空格
- Match and replace with
$1
, which captures a single space
- regular-expressions.info/Anchors
这篇关于Java如何用字符串中的单个空格替换2个或更多空格并删除前导和尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Match and replace with
- 匹配并替换为
查看全文