Java正则表达式通配符详解

正则表达式(Regular Expression)是一种用于匹配、查找和替换文本的强大工具。在Java中,正则表达式由java.util.regex包提供支持。正则表达式通配符是一种特殊的字符,用于描述匹配模式。本文将介绍常用的Java正则表达式通配符及其使用方法。

1. 点字符(.

点字符(.)可以匹配任意字符(除了换行符)。例如,正则表达式a.b可以匹配字符串acbadb等。下面是一个示例代码:

import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        String pattern = "a.b";
        String input1 = "acb";
        String input2 = "adb";
        
        boolean match1 = Pattern.matches(pattern, input1);
        boolean match2 = Pattern.matches(pattern, input2);
        
        System.out.println("Match 1: " + match1);  // true
        System.out.println("Match 2: " + match2);  // true
    }
}

2. 星号字符(*

星号字符(*)可以匹配前面的字符零次或多次。例如,正则表达式a*b可以匹配字符串babaab等。下面是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String pattern = "a*b";
        String input1 = "b";
        String input2 = "ab";
        String input3 = "aab";
        
        boolean match1 = Pattern.matches(pattern, input1);
        boolean match2 = Pattern.matches(pattern, input2);
        boolean match3 = Pattern.matches(pattern, input3);
        
        System.out.println("Match 1: " + match1);  // true
        System.out.println("Match 2: " + match2);  // true
        System.out.println("Match 3: " + match3);  // true
    }
}

3. 加号字符(+

加号字符(+)可以匹配前面的字符一次或多次。例如,正则表达式a+b可以匹配字符串abaab等,但不能匹配字符串b。下面是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String pattern = "a+b";
        String input1 = "ab";
        String input2 = "aab";
        String input3 = "b";
        
        boolean match1 = Pattern.matches(pattern, input1);
        boolean match2 = Pattern.matches(pattern, input2);
        boolean match3 = Pattern.matches(pattern, input3);
        
        System.out.println("Match 1: " + match1);  // true
        System.out.println("Match 2: " + match2);  // true
        System.out.println("Match 3: " + match3);  // false
    }
}

4. 问号字符(?

问号字符(?)可以匹配前面的字符零次或一次。例如,正则表达式a?b可以匹配字符串bab,但不能匹配字符串aab。下面是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String pattern = "a?b";
        String input1 = "b";
        String input2 = "ab";
        String input3 = "aab";
        
        boolean match1 = Pattern.matches(pattern, input1);
        boolean match2 = Pattern.matches(pattern, input2);
        boolean match3 = Pattern.matches(pattern, input3);
        
        System.out.println("Match 1: " + match1);  // true
        System.out.println("Match 2: " + match2);  // true
        System.out.println("Match 3: " + match3);  // false
    }
}

5. 大括号字符({n}

大括号字符({n})可以匹配前面的字符恰好出现n次。例如,正则表达式a{3}b可以匹配字符串aaab,但不能匹配字符串aab。下面是一个示例代码:

public class Main {
    public static void main(String[] args) {
        String pattern = "a{3}b";
        String input1 = "aaab";
        String input2 = "aab";
        
        boolean match1 = Pattern.matches(pattern, input