Java how to replace 2 or more spaces with single s

2018-12-31 21:44发布

Looking for quick, simple way in Java to change this string

" hello     there   "

to something that looks like this

"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("( )+", " ");

but not quite.

19条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 22:11

you should do it like this

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( +)", " ");

put + inside round brackets.

查看更多
何处买醉
3楼-- · 2018-12-31 22:13

Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here

查看更多
高级女魔头
4楼-- · 2018-12-31 22:17
String str = " hello world"

reduce spaces first

str = str.trim().replaceAll(" +", " ");

capitalize the first letter and lowercase everything else

str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
查看更多
牵手、夕阳
5楼-- · 2018-12-31 22:20

This worked for me

scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();

where filter is following function and scan is the input string:

public String filter(String scan, String regex, String replace) {
    StringBuffer sb = new StringBuffer();

    Pattern pt = Pattern.compile(regex);
    Matcher m = pt.matcher(scan);

    while (m.find()) {
        m.appendReplacement(sb, replace);
    }

    m.appendTail(sb);

    return sb.toString();
}
查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 22:21

You can first use String.trim(), and then apply the regex replace command on the result.

查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 22:22

This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");

查看更多
登录 后发表回答