在 Java 里用正则表达式过滤空格,常见有几种“过滤”方式,取决于你想要什么效果。下面按使用场景给你总结。
String input = "a b\tc\nd";
String result = input.replaceAll("\\s+", "");
System.out.println(result); // abcd
✅ 说明:
\\s 匹配所有空白字符(空格、\t、\n、\r)+ 表示连续多个也一起删String result = input.replaceAll(" ", "");
String result = input.trim();
或者用正则(更灵活):
String result = input.replaceAll("^\\s+|\\s+$", "");
String input = "a b c";
String result = input.replaceAll("\\s+", " ");
System.out.println(result); // "a b c"
如果你想自定义要过滤的字符(比如只过滤空格和全角空格):
String input = "a b c"; // 包含全角空格
String result = input.replaceAll("[ \\u3000]+", "");
import java.util.regex.*;
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher("a b c");
String result = matcher.replaceAll("");
❌ 这样写不对:
input.replace("\\s", ""); // 不会生效(没用 regex)
✅ 必须用:
input.replaceAll(...)
| 需求 | 正则 |
|---|---|
| 删除所有空白 | \\s+ |
| 只删空格 | " " |
| 压缩空格 | \\s+ → " " |
| 去首尾空格 | `^\s+ |
如果你有具体场景(比如 JSON、SQL、日志、用户输入),我可以帮你写更精准的正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。