Java正则表达式Pattern和Matcher原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
基本使用
Scanner中的使用正则表达式
//Scanner 支持的分组
Scanner cin=new Scanner("red a bbc").useDelimiter("s*as*");
System.out.println(cin.next());
System.out.println(cin.next());out:
redbbc
等同于下面代码
//等于 正则
Scanner cin2=new Scanner("red a bbc");
cin2.findInLine("s*"); // findLine 允许存在多个,match()为最终需要匹配的字符串
MatchResult result = cin2.match();
for (int i = 0; i < result.groupCount(); i++) {
System.out.println(result.group(i));
}
Pattern:
//基本匹配
boolean b = Pattern.matches("a*b", "aaaab");
System.out.println(b);
String的aplit的实现
//按照数字分割
Pattern p=Pattern.compile("d+");
String[] str=p.split("好456456像:0532214是");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
一般使用Pattern.matches(String regex,CharSequence input)是一个静态方法,用于快速匹配字符串,该方法适合用于只匹配一次,且匹配全部字符串.
Java代码示例:
Pattern.matches("d+","2223");//返回true
Pattern.matches("d+","2223aa");//返回false,需要匹配到所有字符串才能返回true,这里aa不能匹配到
Pattern.matches("d+","22bb23");//返回false,需要匹配到所有字符串才能返回true,这里bb不能匹配到 Pattern p=Pattern.compile("d+"); Matcher m=p.matcher("22bb23"); m.pattern();//返回p 也就是返回该Matcher对象是由哪个Pattern对象的创建的
重点:
matches 方法尝试将整个输入序列与该模式匹配。
lookingAt 尝试将输入序列从头开始与该模式匹配。
find 方法扫描输入序列以查找与该模式匹配的下一个子序列。
// matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
Pattern p=Pattern.compile("d+");
Matcher m=p.matcher("22bb23");
m.matches();//返回false,因为bb不能被d+匹配,导致整个字符串匹配未成功.
Matcher m2=p.matcher("2223");
m2.matches();//返回true,因为d+匹配到了整个字符串
// lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
Pattern p1=Pattern.compile("d+");
Matcher m3=p1.matcher("22bb23");
m.lookingAt();//返回true,因为d+匹配到了前面的22
Matcher m4=p1.matcher("aa2223");
m2.lookingAt();//返回false,因为d+不能匹配前面的aa
// find()对字符串进行匹配,匹配到的字符串可以在任何位置.
Pattern p2=Pattern.compile("d+");
Matcher m5=p2.matcher("22bb23");
m.find();//返回true
Matcher m6=p2.matcher("aa2223");
m2.find();//返回true
Matcher m7=p2.matcher("aa2223bb");
m3.find();//返回true
Matcher m8=p2.matcher("aabb");
m4.find();//返回false










