正则表达式就是用一些规定的字符来制定规则,并来校验数据的合法性。在编写字符串或者网页时,经常会有查找符合某些复杂规则字符串的要求,正则表达式就是用于描述这些规则的工具。
字符类:(默认匹配一个字符)
[abc] 只能是abc
[^abc] 除了abc外任何字符
[a-zA-Z] a-zA-Z 包括范围
[a-d[m-p]] a-dm-p
[a-z&&[def]] d,e,f(交集)
[a-z&&[^bc]] a-z除了bc以外
[a-z&&[^m-p]] a-lq-z a-z除了m-p
预定义的字符类:(默认匹配一个字符)
. 任何字符
\d 一个数字[0-9]
\D 非数字[^0-9]
\s 一个空白字符[\t\n\0B\f\r]
\S 一个非空白字符[^\s]
\w [a-zA-Z_0-9]字母,下划线,数字
\W [^w]
贪婪的量词:(适用于多个字符)
X? X,一次或根本不
X* X,零次或多次
X+ X,一次或多次
X{n} 正好n次
X{n,} 至少n次
X{n,m} 至少n,但不超过m
字符串对象提供了匹配正则表达式的API
public boolean matches(String regex) 判断是否匹配正则表达式,匹配返回true,否则返回false
//校验单个字符
System.out.println("a".matches("[abc]"));//true
System.out.println("z".matches("[abc]"));//false
System.out.println("a".matches("[^abc]"));//false
System.out.println("z".matches("[^abc]"));//true
System.out.println("a".matches("\\d"));//false
System.out.println("3".matches("\\d"));//false
System.out.println("333".matches("\\d"));//false
System.out.println("z".matches("\\w"));//true
System.out.println("2".matches("\\w"));//true
System.out.println("21".matches("\\w"));//false
System.out.println("你".matches("\\w"));//false
System.out.println("*******************************************");
//
//校验密码 必须是字母下划线数字 大于6位小于10位
System.out.println("abc_12".matches("\\w{6,10}"));//true
System.out.println("abc_1".matches("\\w{6,10}"));//false
System.out.println("abc_123456".matches("\\w{6,10}"));//true
System.out.println("abc_1234567".matches("\\w{6,10}"));//false
System.out.println("abc_12你".matches("\\w{6,10}"));//false
//验证必须是 字母数字的,且必须是4位
System.out.println("a3y7".matches("[a-zA-Z0-9]{4}"));//true
System.out.println("a3Z7".matches("[a-zA-Z0-9]{4}"));//true
System.out.println("a3Z7".matches("[\\w&&[^_]]{4}"));//true
System.out.println("a3y7Z".matches("[a-zA-Z0-9]{4,7}"));//false
正则表达式一些常见的案例:
1.模拟输入手机号码,并校验格式正确,并给出提示
public static void inputPhone() {
Scanner sc = new Scanner(System.in);
String str;
while (true){
System.out.println("请输入手机号码");
str = sc.next();
if(str.matches("1[3-9]\\d{9}")){
System.out.println("恭喜您,注册成功");
break;
}else{
System.out.println("格式有误");
}
}
}
2.模拟输入邮箱,并校验格式正确,并给出提示
public static void checkEmail(){
Scanner sc = new Scanner(System.in);
while (true){
System.out.println("请输入你的邮箱");
String str =sc.next();
//****@***.*** 一级邮箱 ****@***.***.*** 二级邮箱
if (str.matches("\\w{1,20}@[a-zA-Z0-9]{1,20}(\\.[a-zA-Z0-9]{1,20}){1,2}")){
break;
}
}
}
3.输入电话号码,并校验格式正确,并给出提示
//0开头 2-7位数字 -可有可无 5-10位数字
if (str.matches("0\\d{2,7}-?\\d{5-10}"))
正则表达式在字符串方法中的使用
public String replaceAll(String regex, String newStr) 根据正则表达式进行替换
public String[] split(String regex) 根据正则表达式进行分割字符串
String names ="张三2334dshhs李四hhhhsjj2王五";
String[] splits = names.split("\\w+");
System.out.println(Arrays.toString(splits));//[张三, 李四, 王五]
String name2 = names.replaceAll("\\w+"," ");
System.out.println(name2);//张三 李四 王五