首页 > 基础教程 > 正则表达式 > Matcher类
Java Matcher.lookingAt()部分匹配字符串
Matcher.lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true。
定义
public boolean lookingAt()
例子
实例一
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher("22bb23");
m.lookingAt();//返回true,因为\d+匹配到了前面的22
Matcher m2=p.matcher("aa2223");
m2.lookingAt();//返回false,因为\d+不能匹配前面的aa
实例二
public static void main(String arg[]) {
String string = "123-34345-234-00";
Pattern pattern = Pattern.compile("\\d{3,5}");
Matcher matcher = pattern.matcher(string);
boolean result1 = matcher.matches();
System.out.println("result1=" + result1);
//重置匹配器。
matcher.reset();
//尝试查找与该模式匹配的输入序列的下一个子序列。
boolean result2 = matcher.find();
System.out.println("result2=" + result2);
boolean result3 = matcher.find();
System.out.println("result3=" + result3);
boolean result4 = matcher.find();
System.out.println("result4=" + result4);
boolean result5 = matcher.find();
System.out.println("result5=" + result5);
//尝试将从区域开头开始的输入序列与该模式匹配。
boolean result6 = matcher.lookingAt();
System.out.println("result6=" + result6);
boolean result7 = matcher.lookingAt();
System.out.println("result7=" + result7);
boolean result8 = matcher.lookingAt();
System.out.println("result8=" + result8);
}
运行结果:
result1=false
result2=true
result3=true
result4=true
result5=false
result6=true
result7=true
result8=true
总结
lookingAt是部分匹配,总是从第一个字符进行匹配,匹配成功了不再继续匹配,匹配失败了,也不继续匹配。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。