1.正则表达式的作用:用来判断一个字符串是否符合指定要求.
正则表达式的好处:简化判断代码.
2.正则规则:
预定义字符类
. 任意字符(与行结束符可能匹配也可能不匹配)
\d 数字:[0-9] \w 单词字符:[a-zA-Z_0-9]
边界匹配器
^ 行开头
$ 行结尾
数量:
X? 一次或0次
X* 0次或多次(包括1次)
X+ 一次或多次
X{n} 恰好n次
X{n,} 至少n次
X{n,m} 至少n次,不超过m次
4.判断字符串是否全部匹配一个正则表达式:字符串变量.matches(正则表达式).
eg:public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个QQ邮箱:");
String email=input.next();
//声明一个QQ邮箱的正则表达式
String reg="([1-9]\\d{4,10}@qq.com)|([a-zA-Z]{5,11}@qq.com)";
//判断QQ邮箱
if (email.matches(reg)) {
System.out.println("你输入的QQ邮箱正确!");
} else {
System.out.println("你输入的QQ邮箱有误!");
}
}
原生态正则表达式的使用:局部匹配时才会使用,全局匹配可String类方法更简单.
Pattern:正则表达式的编译表示形式。
常用方法:
compile(String regex) 将给定的正则表达式编译到模式中。
matcher(CharSequence input) 创建匹配给定输入与此模式的匹配器(Matcher)。
Matcher:匹配器类.
matches() 尝试将整个字符串与正则表达式匹配(全局匹配)。
find()尝试从字符串的开头开始一部分一部分匹配正则表达式.(局部匹配)。
group() 返回由find()局部匹配子字符串。
eg:public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个手机号:");
String phone=input.next();
/*第三种:用原生态正则类来判断手机号*/
//创建正则表达式对象,要将正则表达式作为参数
Pattern p=Pattern.compile("1[3-9]\\d{9}");
//用正则表达式对象创建匹配器对象,且要将匹配的字符串作为参数
Matcher m=p.matcher(phone);
//判断字符串是否全局匹配正则表达式
if (m.matches()) {
System.out.println("你输入的手机号正确");
}else {
System.out.println("你输入的手机号有误!");
}
/*第二种:String类的matches判断手机号*/
// //声明正则表达式
// String reg1="1[3-9]\\d{9}";
// //判断字符串是否符合正则表达式
// if (phone.matches(reg1)) {
// System.out.println("你输入的手机号正确");
// }else {
// System.out.println("你输入的手机号有误!");
// }
/*第一种:用选择结构判断手机号*/
// if (phone.length()==11) {
// //将手机字符串转换为字符数组
// char[] cs=phone.toCharArray();
// //判断手机号的每一位,开头只能是1,第二位只能3-9,其他位是0-9数字
// if (cs[0]!='1') {
// System.out.println("你输入的手机号第一位有误!");
// }else if(!(cs[1]<='9'&&cs[1]>='3')) {
// System.out.println("你输入的手机号第二位有误!");
// }else {
// //声明一个变量作标记,标记手机号其他位是否有误,默认没误
// boolean flag=true;
// //判断手机号的每一位,其他位是0-9数字
// for (int i = 3; i < cs.length; i++) {
// if (!(cs[i]>='0'&&cs[i]<='9')) {
// System.out.println("你输入的手机号有误!");
// flag=false;
// break;
// }
// }
//
// if (flag) {
// System.out.println("你输入的手机号正确");
// }
// }
//
// } else {
// System.out.println("你输入的手机号位数错误!");
// }
}
eg:局部匹配手机号
public static void main(String[] args) {
String word="我的一个手机号是15179096236,另一个手机号是15112603730,可以打电话联系我";
System.out.println("原话为:"+word);
//创建正则表达式对象,要将正则表达式作为参数
Pattern p=Pattern.compile("1[3-9]\\d{9}");
//用正则表达式对象创建匹配,将要匹配字符串作为参数
Matcher m=p.matcher(word);
//从头判断这个字符串有没匹配部分
while (m.find()==true) {
//获得匹配的部分
String oldPhone=m.group();
//屏蔽手机中间五位
String newPhone=oldPhone.substring(0, 3)+"*****"+oldPhone.substring(8, 11);
//将原手机号替换为屏蔽后手机号
word=word.replace(oldPhone, newPhone);
}
System.out.println("屏蔽后话为:"+word);
}