在Java正则表达式中使用字符类
字符类是一组用方括号括起来的字符。字符类中的字符指定可以与输入字符串中的字符匹配以成功的字符。字符类的一个示例是[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());
}热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短