在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 婆婆高寿祝福语大全简短