在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 送给学长毕业祝福语简短