438. Java 正则表达式 - 简介

文章目录

  • [438. Java 正则表达式 - 简介](#438. Java 正则表达式 - 简介)
    • [1. 什么是正则表达式(Regular Expressions)](#1. 什么是正则表达式(Regular Expressions))
    • [2. Java 的正则表达式核心类](#2. Java 的正则表达式核心类)
      • [🌰 示例:Pattern 和 Matcher](#🌰 示例:Pattern 和 Matcher)
    • [3. Unicode 支持(JDK 7+)](#3. Unicode 支持(JDK 7+))
      • [匹配指定的 Unicode 码点](#匹配指定的 Unicode 码点)
      • [Unicode 属性匹配](#Unicode 属性匹配)
    • [4. 总结 🎯](#4. 总结 🎯)

438. Java 正则表达式 - 简介

1. 什么是正则表达式(Regular Expressions)

正则表达式(简称 Regex)是一种用来 描述字符串模式 的工具。它能帮我们完成:

  • 🔍 搜索文本(比如:找出所有手机号)
  • ✂️ 编辑和替换文本(比如:把日期格式从 2025-09-16 改成 16/09/2025
  • ✅ 验证输入(比如:检查用户输入是不是合法的邮箱地址)

👉 正则表达式有点像一门小语言,它有自己独特的语法规则,比普通的 Java 语法要"紧凑"。一开始可能觉得晦涩,但掌握了基本规则之后,就可以快速看懂、甚至写出复杂的正则。

在业界,有多种"方言":grepPerlTclPythonPHPawk 等。Java 的正则表达式语法和 Perl 最接近。


2. Java 的正则表达式核心类

Java 的正则表达式主要由 java.util.regex 包里的三个核心类组成:

  • Pattern
    已编译的正则表达式对象。
    👉 用 Pattern.compile() 创建,而不是 new。
  • Matcher
    正则引擎,用来匹配输入字符串。
    👉 通过 pattern.matcher("input") 获取。
  • PatternSyntaxException
    当正则语法错误时抛出的异常。
    👉 例如 Pattern.compile("[A-Z") 会报错,因为右括号缺失。

🌰 示例:Pattern 和 Matcher

java 复制代码
import java.util.regex.*;

public class RegexDemo {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+"); // 匹配一个或多个数字
        Matcher matcher = pattern.matcher("Today is 2025-09-16.");

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group() +
                " from index " + matcher.start() +
                " to " + matcher.end());
        }
    }
}

输出:

java 复制代码
Found: 2025 from index 9 to 13
Found: 09 from index 14 to 16
Found: 16 from index 17 to 19

👉 解释:

  • \\d+ 表示匹配一个或多个数字
  • matcher.find() 会逐个找出所有符合的子串

3. Unicode 支持(JDK 7+)

Java 的正则在 JDK 7 以后支持 Unicode 6.0,更适合国际化场景。

匹配指定的 Unicode 码点

  • \uFFFF 格式"\u6771" → 匹配"東"字(汉字"东"的繁体)。

    java 复制代码
    int codePoint = 0x6771;
    String hexPattern = String.format("\\u%04x", codePoint);
    
    Pattern pattern = Pattern.compile(hexPattern);
    Matcher matcher = pattern.matcher("東风破");
    System.out.println(matcher.find()); // true

Unicode 属性匹配

可以按照字符的"脚本 (script)"、"区块 (block)"和"通用类别 (general category)"匹配。

  • 脚本 (Scripts)
    \p{script=Hiragana}\p{IsHiragana}
    👉 用来匹配日语平假名。
  • 区块 (Blocks)
    \p{block=Mongolian}\p{InMongolian}
    👉 用来匹配蒙古文字符。
  • 通用类别 (General Category)
    • \p{IsL} → 匹配所有字母
    • \p{gc=Lu} → 匹配所有大写字母
    • \p{gc=Nd} → 匹配所有数字

🌰 示例:

java 复制代码
Pattern p = Pattern.compile("\\p{IsHiragana}+"); // 匹配平假名
Matcher m = p.matcher("これはテストです"); // 包含日语平假名
System.out.println(m.find()); // true

4. 总结 🎯

  • 正则表达式是 强大的字符串模式工具

  • Java 提供 Pattern + Matcher 来完成匹配

  • JDK 7 起支持 Unicode 6.0,能处理国际化文本