版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37012236/article/details/80308557
一、
正则的作用有很多种,可以校验字符,可以截取字符串等。
正则的普通用法大家应该都很熟悉,但是他的开始符(^)和结束符($)有什么作用呢,大家看以下手机号正则:
^1\\d{10}$
1、你会发现 ^1\\d{10}$ 与 1\\d{10}$ 都可以匹配手机号字符串,但是 ^1\\d{10}$ 表示了整个字符串不能有手机号其他的字符,如 "小明手机18311131865",此字符串则与^1\\d{10}$是无法匹配的,应为字符串不是已手机号开头结尾的.
2、 那么截取字符串大家想一下应该用第二种还是第一种呢?显而易见是第二种:
@Test
public void test44(){
String phonrNul = "我的13241324,地方";
Pattern compile = Pattern.compile("\\d{2,}");
Matcher matcher = compile.matcher(phonrNul);
if(matcher.find()){
log.info("lllllllllll:{}",matcher.group());
log.info("wwwwwwwwwww:{}",matcher.group(1));
}
}
请注意 boolean a = matcher.matches() ; 与 boolean b = matcher.find() ; 的区别
请注意 matcher.group() ; 与 ,matcher.group(1) ; 的区别