前言
我们需要对用户输入的值进行限制,怎么解决?
许多很帅的的想出来使用js/jqyery的正则表达式就可以了
那我在想java中有正则表达式么?
答案是有的,java的api中为我们提供了正则表达式的支持类------Pattern
必备知识
1.正则表达式规则和js/jquery一样
2.除了以上的用途还可以用来搜索,编辑或处理文本
3.java中正则表达式斜杠需要使用\\
使用
1.编写字符串和正则表达式
2.获取Pattern 传入正则表达式
3.获取matche对象,传入字符串
4.调用mathcher()方法判断结果
代码测试
String a="aaaa@163.com";
String pat="^[a-zA-Z0-9]{4,12}+@(qq.com|163.com|126.com)$";//正则表达式规则
Pattern r = Pattern.compile(pat);//获取Pattern对象 传入正则表达式
Matcher m = r.matcher(a);//获取matcher对象 传入字符串
System.out.println(m.matches());
结果
false
Process finished with exit code 0
常用方法
1.matcher的find()查询是否有此字符串,避免其他字符干扰 相当于contain()
2.matcher的group() 按照正则表达式规则将需要的信息打印出来使用group前必须使用find()否则报错 No match found
3.字符串里若有多个需要的信息,可以使用while循环打印出来
代码演示
//以下为find方法演示
String s=" 张三 电话:13146579820 16578946260爱好15976302542:打球 12589643750";
String str1="1\\d{10}";
Pattern c1 = Pattern.compile(str1);
Matcher m2 = c1.matcher(s);
System.out.println(m2.find());
System.out.println("-----------------------------");
//以下为group方法演示
String str2="(1\\d{10})";
Pattern c2 = Pattern.compile(str2);
Matcher m3 = c2.matcher(s);
m3.find();
System.out.println(m3.group());
System.out.println("-----------------------------");
//以下为whlie循环演示
while (m3.find()){
System.out.println(m3.group());
}
结果
true
-----------------------------
13146579820
-----------------------------
16578946260
15976302542
12589643750
Process finished with exit code 0
这里为什么只打印3个电话呢?
以为第一个使用了两个group方法,也就是说这个方法可以去重,不打印已经出现的东西
二次测试
//以下为find方法演示
String s=" 张三 电话:13146579820 16578946260爱好15976302542:打球 12589643750";
String str1="1\\d{10}";
Pattern c1 = Pattern.compile(str1);
Matcher m2 = c1.matcher(s);
System.out.println(m2.find());
System.out.println("-----------------------------");
//以下为group方法演示
String str2="(1\\d{10})";
Pattern c2 = Pattern.compile(str2);
Matcher m3 = c2.matcher(s);
// m3.find();
// System.out.println(m3.group());
System.out.println("-----------------------------");
//以下为whlie循环演示
while (m3.find()){
System.out.println(m3.group());
}
结果
true
-----------------------------
-----------------------------
13146579820
16578946260
15976302542
12589643750
Process finished with exit code 0