Java 中的正则表达式空格
    
    Rupam Yadav
    2023年10月12日
    
    Java
    Java Regex
    Java Regex
    
 
正则表达式或 regex 是特殊字符的组合,可创建可用于搜索字符串中某些字符的搜索模式。在下面的示例中,我们将看到如何使用各种正则表达式字符来查找字符串中的空格。
在 Java 中使用正则表达式查找空格
要使用正则表达式搜索模式并查看给定的字符串是否与正则表达式匹配,我们使用类 Pattern 的静态方法 matches()。matches() 方法有两个参数:第一个是正则表达式,第二个是我们要匹配的字符串。
查找空格最常见的正则表达式字符是\s 和\s+。这些正则表达式字符之间的区别在于,\s 表示单个空格字符,而\s+ 表示字符串中的多个空格。
在下面的程序中,我们使用 Pattern.matches() 来检查使用正则表达式 \s+ 的空格,然后是具有三个空格的字符串。然后,我们打印输出 true 的 whitespaceMatcher1,这意味着模式匹配并找到空格。
在 whitespaceMatcher2 中,我们使用字符\s 来识别单个空格,它对字符串" "返回 true。请注意,正则表达式区分大小写,并且\S 与\s 不同。
接下来,我们使用正则表达式 [\\t\\p{Zs}],它等效于\s,并为单个空格返回 true。
\u0020 是一个表示空格的 Unicode 字符,当传递带有单个空格的字符串时返回 true。
最后一个正则表达式 \p{Zs} 也是一个标识空白的空白分隔符。
import java.util.regex.Pattern;
public class RegWhiteSpace {
  public static void main(String[] args) {
    boolean whitespaceMatcher1 = Pattern.matches("\\s+", "   ");
    boolean whitespaceMatcher2 = Pattern.matches("\\s", " ");
    boolean whitespaceMatcher3 = Pattern.matches("[\\t\\p{Zs}]", " ");
    boolean whitespaceMatcher4 = Pattern.matches("\\u0020", " ");
    boolean whitespaceMatcher5 = Pattern.matches("\\p{Zs}", " ");
    System.out.println("\\s+ ----------> " + whitespaceMatcher1);
    System.out.println("\\s -----------> " + whitespaceMatcher2);
    System.out.println("[\\t\\p{Zs}] --> " + whitespaceMatcher3);
    System.out.println("\\u0020 ------->" + whitespaceMatcher4);
    System.out.println("\\p{Zs} ------->" + whitespaceMatcher5);
  }
}
输出:
\s+ ----------> true
\s -----------> true
[\t\p{Zs}] --> true
\u0020 ------->true
\p{Zs} ------->true
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Rupam Yadav
    Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn