杰瑞科技汇

Java正则如何匹配任意字符?

(点号)

  • 含义:匹配除换行符(\n)外的任意单个字符。
  • 示例
    String regex = ".";
    System.out.println("a".matches(regex)); // true
    System.out.println(" ".matches(regex)); // true
    System.out.println("\n".matches(regex)); // false

\d

  • 含义:匹配任意数字(等价于 [0-9])。
  • 示例
    String regex = "\\d"; // 注意:Java 中需要双反斜杠 "\\d"
    System.out.println("5".matches(regex)); // true
    System.out.println("a".matches(regex)); // false

\w

  • 含义:匹配任意单词字符(字母、数字、下划线,等价于 [a-zA-Z0-9_])。
  • 示例
    String regex = "\\w";
    System.out.println("a".matches(regex)); // true
    System.out.println("_".matches(regex)); // true
    System.out.println("@".matches(regex)); // false

\s

  • 含义:匹配任意空白字符(空格、制表符 \t、换行符 \n 等)。
  • 示例
    String regex = "\\s";
    System.out.println(" ".matches(regex)); // true
    System.out.println("\t".matches(regex)); // true
    System.out.println("a".matches(regex)); // false

+ DOTALL 模式

  • 需求:匹配包括换行符在内的任意字符。

  • 方法:使用 Pattern.DOTALL 标志。

  • 示例

    String text = "a\nb";
    String regex = "."; // 默认不匹配换行符
    System.out.println(text.matches(regex)); // false
    Pattern pattern = Pattern.compile(".", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(text);
    System.out.println(matcher.matches()); // true

[\s\S]

  • 含义:匹配任意字符(包括换行符),因为 \s 匹配空白字符,\S 匹配非空白字符,两者合起来覆盖所有字符。
  • 示例
    String regex = "[\\s\\S]"; // 注意:Java 中需要双反斜杠
    System.out.println("a".matches(regex)); // true
    System.out.println("\n".matches(regex)); // true

*`..+`**

  • 含义:匹配任意字符(包括换行符,需结合 DOTALL)或任意多个/一个字符。

  • 示例

    String text = "abc\ndef";
    String regex = ".*"; // 默认不匹配跨行
    System.out.println(text.matches(regex)); // false
    Pattern pattern = Pattern.compile(".*", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(text);
    System.out.println(matcher.matches()); // true

需求 正则表达式 说明
任意字符(不含换行) 默认行为
包含换行的任意字符 [\s\S] 跨行匹配
数字 \d 等价于 [0-9]
单词字符 \w 等价于 [a-zA-Z0-9_]
空白字符 \s 空格、制表符、换行符等
所有字符(跨行) + DOTALL 需启用 Pattern.DOTALL 标志

根据你的具体需求选择合适的正则表达式!

分享:
扫描分享到社交APP
上一篇
下一篇