在 Java 中,匹配空白符(whitespace)有几种常见方式,下面按使用场景说明。
\s\s 在正则中表示任意空白字符,包括:
' '\t\n\r\fString text = "hello\tworld\njava";
String regex = "\\s";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("找到空白符: [" + matcher.group() + "]");
}
⚠️ 注意:
在 Java 字符串中,\ 需要转义,所以写成 "\\s"
String regex = "\\s+";
常用于:
String.splitString text = "a b\tc\nd";
String[] parts = text.split("\\s+");
如果你只想要普通空格:
String regex = " ";
String regex = "\\S"; // 非空白字符
String result = text.replaceAll("\\s+", "");
如果你有具体场景(比如:去除首尾空格、保留一个空格、解析日志等),可以告诉我,我可以直接给你对应代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。