杰瑞科技汇

Java正则如何匹配空格?

Java 正则表达式匹配空格

在 Java 中,可以使用正则表达式来匹配各种类型的空格字符,以下是几种常见情况的实现方法:

Java正则如何匹配空格?-图1
(图片来源网络,侵删)

匹配所有空白字符(包括空格、制表符、换行等)

String regex = "\\s+"; // 一个或多个空白字符
String input = "This is a test\twith\nmultiple spaces";
String[] parts = input.split(regex);
System.out.println(Arrays.toString(parts)); 
// 输出: [This, is, a, test, with, multiple, spaces]

仅匹配空格字符(不包括制表符、换行等)

String regex = " +"; // 一个或多个空格
String input = "This is  a test   with  multiple  spaces";
String[] parts = input.split(regex);
System.out.println(Arrays.toString(parts)); 
// 输出: [This, is, a, test, with, multiple, spaces]

匹配前导和尾随空格

String regex = "^\\s+|\\s+$"; // 行首或行尾的一个或多个空白字符
String input = "   This is a test   ";
String result = input.replaceAll(regex, "");
System.out.println(result); // 输出: "This is a test"

匹配单词之间的空格(非单词边界)

String regex = "(?<=\\S)\\s+(?=\\S)"; // 匹配两个非空白字符之间的空白
String input = "This is  a test   with  multiple  spaces";
String result = input.replaceAll(regex, " ");
System.out.println(result); // 输出: "This is a test with multiple spaces"

检查字符串是否包含空格

String regex = ".*\\s.*"; // 包含至少一个空白字符
String input1 = "no spaces";
String input2 = "has spaces";
System.out.println(input1.matches(regex)); // 输出: false
System.out.println(input2.matches(regex)); // 输出: true

常用空白字符说明

  • \\s - 任何空白字符(包括空格、制表符 \t、换行符 \n、回车符 \r、换页符 \f
  • ` ` - 仅匹配空格字符
  • \\t - 制表符
  • \\n - 换行符
  • \\r - 回车符
  • \\f - 换页符

根据你的具体需求,选择合适的正则表达式模式即可。

Java正则如何匹配空格?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇