📌  相关文章
📜  Java正则表达式-匹配字符类(1)

📅  最后修改于: 2023-12-03 14:43:01.658000             🧑  作者: Mango

Java正则表达式-匹配字符类

正则表达式是用于匹配字符串中符合某种规律的文本。 Java中通过java.util.regex包来支持正则表达式的使用。

在正则表达式中,字符类(也称字符集)是用来匹配一组字符中的任意一个字符。字符类是用方括号[]括起来的一组字符。

以下是一些常用的字符类:

| 字符类 | 描述 | |--------|-----| | [abc] | 匹配a、b、c中的任意一个字符 | | [^abc] | 匹配除了a、b、c之外的任意一个字符 | | [a-z] | 匹配所有小写字母 | | [A-Z] | 匹配所有大写字母 | | [0-9] | 匹配所有数字字符 | | [a-zA-Z] | 匹配所有字母 | | [a-zA-Z0-9] | 匹配所有字母和数字字符 | | [\u4e00-\u9fa5] | 匹配所有中文字符 |

在字符类中可以使用连字符(-)来表示一个字符范围,例如[a-z]表示匹配所有小写字母。 也可以在字符类中使用特殊字符转义来表示特殊字符,例如^表示匹配^字符。

以下是一个示例程序:

import java.util.regex.*;

public class CharacterClassExample {
    public static void main(String[] args) {
        String text = "Hello 123 World!";
        
        // 匹配所有数字字符
        Pattern pattern1 = Pattern.compile("[0-9]");
        Matcher matcher1 = pattern1.matcher(text);
        while (matcher1.find()) {
            System.out.println(matcher1.group());
        }
        
        // 匹配所有字母和数字字符
        Pattern pattern2 = Pattern.compile("[a-zA-Z0-9]");
        Matcher matcher2 = pattern2.matcher(text);
        while (matcher2.find()) {
            System.out.println(matcher2.group());
        }
        
        // 匹配所有非数字字符
        Pattern pattern3 = Pattern.compile("[^0-9]");
        Matcher matcher3 = pattern3.matcher(text);
        while (matcher3.find()) {
            System.out.println(matcher3.group());
        }
    }
}

输出结果为:

1
2
3
H
e
l
l
o
W
o
r
l
d
!
H
e
l
l
o
 
W
o
r
l
d
!

以上程序演示了如何使用字符类来匹配文本中的字符。通过Pattern和Matcher对象的组合,我们可以编写出更为复杂的正则表达式,实现更加精确的匹配功能。