String.replaceAll奇怪的行为 [英] String.replaceAll Strange Behaviour

查看:94
本文介绍了String.replaceAll奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String s = "hi                  hello";
s = s.replaceAll("\\s*", " ");
System.out.println(s);

我有上面的代码,但我无法弄清楚它产生的原因

I have the code above, but I can't work out why it produces

 h i  h e l l o 

而不是比

 hi hello

非常感谢

推荐答案

使用 + 量词来匹配1个或多个空格而不是 * : -

Use + quantifier to match 1 or more spaces instead of *: -

s = s.replaceAll("\\s+", " ");

\\\\ * 表示匹配0个或更多空格,并在每个字符前匹配一个空字符,并用空格替换。

\\s* means match 0 or more spaces, and will match an empty character before every character and is replaced by a space.

这篇关于String.replaceAll奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆