在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());
}热门推荐
4 哈尼族祝福语简短
10 海南考试祝福语结婚简短
11 9字虎年简短祝福语
12 送礼祝福语简短有深意
13 岁月有芬芳祝福语简短
14 送朋友搞笑简短祝福语
15 送给新娘祝福语简短高级
16 冬至祝福语简短走心
17 奶奶的生日简短祝福语
18 新年祝福语简短小猪