一.正则表达式总结
一.常用格式
1. a[bcde]f
abf、acf、adf、aef
2. a[b|c|de]f
abf、acf、adef
3. \d
[0-9]
4. \w
[0-9A-Z_a-z]
5. \b
单词分隔符
6. ^
行的开头
7. $
行的结尾
8. \s
[\t\n\r\f]
二.控制个数
1. *
零个一个或多个
2. +
一个或多个
3. ?
零个或一个
4. {n}
正好n个
5. {n,m}
n-m个之间
6. {n,}
至少n个
三.注意易错格式
1. \\
表示反斜线"\"
2. .
表示任意字符
3. \.
表示字符"."
4. \\\\
表示"\\"
二.正则表达式功能应用
1.判断功能(模拟邮箱注册)
package Pers.Pluto.Day02;
import java.util.Scanner;
/*
* 模拟邮箱注册
* 邮箱格式举例如下:
* [email protected]
* [email protected]
* [email protected]
* [email protected]
*
*/
public class RegexDemo {
public static void main(String[] args) {
while(true) {
//键盘输入邮箱
System.out.println("请输入邮箱:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
//定义规则
String regex = "\\D{0,5}\\d{6,10}@(qq|outlook|163)\\.com";
//调用方法检测
boolean flag = str.matches(regex);
System.out.println(flag);
}
}
}
2.分割功能(模拟年龄范围搜索)
package Pers.Pluto.Day02;
/*
* 模拟年龄范围搜素
* 给出年龄范围字符串"18-24"
* 给出分割规则"-"
* 定义字符串数组接收分割后的字符串
*
*/
public class RegexDemo01 {
public static void main(String[] args) {
//给出分割规则
String regex = "-";
//给出年龄范围字符串
String ages = "18-24";
//定义字符串数组接收分割后的字符串
String[] strArray = ages.split(regex);
//将所接收的字符串转换为int类型
int startAge = Integer.parseInt(strArray[0]);
int endAge = Integer.parseInt(strArray[1]);
//打印结果
System.out.println("startAge:"+startAge+"---endAge:"+endAge);
}
}
3.替换功能(模拟qq密码隐藏)
package Pers.Pluto.Day02;
import java.util.Scanner;
public class RegexDemo02 {
public static void main(String[] args) {
//键盘输入密码
System.out.println("请输入密码");
Scanner sc = new Scanner(System.in);
String pwd = sc.nextLine();
//定义替换规则,
String regex = "\\d";
//这里演示将数字用*替换
String result = pwd.replaceAll(regex,"*");
System.out.println(result);
}
}
4.获取功能(Pattern类和Matcher类的常规使用)
package Pers.Pluto.Day02;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo03 {
public static void main(String[] args) {
//定义一个测试字符串
String line = "abcd123efg [email protected]*[email protected]";
//将正则表达式编译到模式中
Pattern p = Pattern.compile("\\b\\w{6,16}\\b(@outlook.com)");
//通过模式对象得到匹配器对象
Matcher m = p.matcher(line);
//注意调用group()方法之前必须先调用find()方法
while(m.find()){
System.out.println(m.group());
//打印结果如下:
//[email protected]
//[email protected]
}
}
}