字符类是一组用方括号括起来的字符。字符类中的字符指定可以与输入字符串中的字符匹配以成功的字符。字符类的一个示例是[az],它表示字母a到z。
给出了一个演示Java正则表达式中的字符类的程序,如下所示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("the sky is blue");
System.out.println("The input string is: the sky is blue");
System.out.println("The Regex is: [a-z]+");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}
}
}输出结果
The input string is: the sky is blue The Regex is: [a-z]+ Match: the Match: sky Match: is Match: blue
现在让我们了解上面的程序。
在字符串序列“天空是蓝色”中搜索子序列“ [az] +”。此处使用字符类,即[az],表示字母a到z。该find()方法用于查找子序列是否在输入序列中,并打印所需的结果。演示此代码段如下:
Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("the sky is blue");
System.out.println("The input string is: the sky is blue");
System.out.println("The Regex is: [a-z]+");
System.out.println();
while (m.find()) {
System.out.println("Match: " + m.group());
}