可以使用空格字符 \s 进行匹配。例如,匹配一个字符串中的所有空格可以使用下面的代码:

String text = "Hello   World";
String pattern = "\\s+";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

while (m.find()) {
    System.out.println("Match found: " + m.group());
}

输出结果:

Match found:   
Match found:   

解释:

  • \s 匹配任意空白字符,包括空格、制表符、换行符等。
  • + 表示匹配前面的字符或字符集一次或多次。因此,\s+ 表示匹配一个或多个空白字符。
Java正则匹配空格

原文地址: https://www.cveoy.top/t/topic/bgig 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录