Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
String s = "hi hello"; s = s.replaceAll("\\s*", " "); System.out.println(s);
我有上面的代码,但我无法弄清楚它为什么会产生
h i h e l l o
而不是
hi hello
非常感谢
使用+量词匹配 1 个或多个空格,而不是*:-
+
*
s = s.replaceAll("\\s+", " ");
\\s*表示匹配 0 个或多个空格,并且会在每个字符之前匹配一个空字符并替换为一个空格。
\\s*
*匹配 0 个或多个空格,我想您想将其更改为+匹配 1 个或多个空格。