温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用java regex过滤空格

发布时间:2026-10-04 21:22:14 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

在 Java 里用正则表达式过滤空格,常见有几种“过滤”方式,取决于你想要什么效果。下面按使用场景给你总结。


一、删除所有空格(最常见)

1️⃣ 删除所有空格(包括普通空格、Tab、换行)

String input = "a b\tc\nd";
String result = input.replaceAll("\\s+", "");
System.out.println(result); // abcd

✅ 说明:

  • \\s 匹配所有空白字符(空格、\t、\n、\r)
  • + 表示连续多个也一起删

2️⃣ 只删除普通空格(不删 Tab / 换行)

String result = input.replaceAll(" ", "");

3️⃣ 删除首尾空格(推荐用 trim)

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

四、使用 Pattern(性能更好,多次使用)

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、日志、用户输入),我可以帮你写更精准的正则。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手