Java 正则表达式

Pattern/Matcher 的用法、捕获组、正则语法与常用方法。

Intermediate
Key PointsString.matches 要求整串匹配;要找子串用 Pattern/Matcher 的 find;分组用 () 提取。

java.util.regex 包

Two core classes: Pattern is the compiled regex and Matcher performs matching on a specific string. For simple cases use String.matches, split or replaceAll directly.

Java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Basic {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("abc123def456");

        System.out.println(m.find());
        System.out.println(m.group());
        System.out.println("123".matches("\\d+"));
        System.out.println("abc123".matches("\\d+"));
    }
}
Output
true
123
true
false

捕获组

Parentheses create capture groups; group(1), group(2) follow the order of opening brackets, and group(0) is the whole match. Named groups use (?<name>...) read via group("name").

Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Groups {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
        Matcher m = p.matcher("date: 2024-10-31");

        if (m.find()) {
            System.out.println(m.group(0));
            System.out.println(m.group(1));
            System.out.println(m.group(2));
            System.out.println(m.groupCount());
        }
    }
}
Output
2024-10-31
2024
10
3

正则表达式语法

The grammar matches other languages: . any character, \d digit, \w word char, \s whitespace, * + ? quantifiers, {m,n} counts, [] sets, ^ $ anchors, | alternation. In Java, backslashes are doubled.

Java
public class Syntax {
    public static void main(String[] args) {
        System.out.println("a1".matches("[a-z]\\d"));
        System.out.println("abc".matches("a.c"));
        System.out.println("12345".matches("\\d{3,5}"));
        System.out.println("2024".matches("^(19|20)\\d{2}$"));
        System.out.println("a@b.com".matches("\\w+@\\w+\\.\\w+"));
    }
}
Output
true
true
true
true
true

Matcher 常用方法

matches() requires the whole string, find() looks for the next match, lookingAt() matches from the start, replaceAll / replaceFirst substitute, group() returns the text. Loop on find to walk every match.

Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("a1b22c333");

        int count = 0;
        while (m.find()) {
            count++;
            System.out.print(m.group() + " ");
        }
        System.out.println();
        System.out.println(count);

        System.out.println("a1b22".replaceAll("\\d+", "#"));
        System.out.println(p.matcher("a1b22").replaceFirst("*"));
    }
}
Output
1 22 333 
3
a#b#
a*b22

Friends & Partners