正则表达式
- 正则表达式,也叫规则表达式,使用一些特定的符号来制定一个规则,使用此规则与一个字符串进行模式匹配, 匹配成功返回true,否则返回false。
- 有了正则表达式,我们就可以用很少甚至一行代码就可以把一些复杂的字符串组合进行匹配,而不需要用一连串的循环和条件语句。
//典型的调用序列
Pattern p = Pattern.compile("a*b");//定义一个规则,“*”表示左边的字符可以出现0次或多次
Matcher m = p.matcher("aaaab");//输入内容
boolean b = m.matches();//匹配
System.out.println(b);//true
//Pattern类定义了一个matches方法,以便在正则表达式只使用一次时方便。
boolean b = Pattern.matches("a*b", "aaaaab");
- 在String类中也有一个matches方法,用来匹配字符串
String s = "abc";
boolean b = s.matches("a*b");
System.out.println(b);//false
- 在Pattern类有一个split(CharSequence input)方法,用于分隔字符串,并返回一个String[],String类中的split(String regex)就是通过Pattern.split(CharSequence input)来实现的.
Pattern p=Pattern.compile("\\d+"); // \d表示数字
String[] str=p.split("我的手机号:139654我的微信号:ps654");
//结果:str[0]="我的手机号:",str[1] = "我的微信号:ps"
String str1 = "姓名:xxx&年龄:xx&身高:xx";
String [] strings = str1.split("&");//规定一个分隔符
System.out.println(Arrays.toString(strings));//[姓名:xxx, 年龄:xx, 身高:xx]
常用的正则表达式
案例
-
验证手机号
//手机号 第一位必须是1,第二位只能是35789中的一个,后面可以是任意0-9之间的数字,一共11位 String phonenum = "13359846854"; String phonenum1 = "1499999999"; System.out.println(phonenum.matches("1[35789]\\d{9}"));// true System.out.println(phonenum1.matches("1[35789]\\d{9}"));//false
-
验证qq号
//qq号 第一位不能是0,后面的是任意0-9数字 6-12位 String qq = "318558420"; String qq1 = "0659461565"; System.out.println(qq.matches("[1-9][0-9]{5,11}"));//true System.out.println(qq1.matches("[1-9]\\d{5,11}"));//false
-
验证邮箱
//邮箱 String email = "dd31855_@qq.com"; String eamil1 = "q.e64sdf_f@sdfg.com.cn"; System.out.println(email.matches("\\w{8}@\\w{1,3}\\.(com|com\\.cn)"));//true System.out.println(eamil1.matches("\\w{8}@\\w{1,3}\\.(com|com\\.cn)"));//false