正则表达式
正则表达式,又称规则表达式,他是一门独立的语法,其他语言都会支持他。
作用: 用来校验数据,符不符合我所定义正则表达式的规则
规则:
String regx = "a";
regx = "[a,b,c]"; //只要是我这里面的一个就行
regx = "[1,2,3,4,5,6,7,8,9]";
regx = "[^0-9]"; //不是我列表中的某一个
regx = "[A-Za-z0-9]";
regx = ".";//通配符,统配任意单个字符
regx = "\\."; //只匹配 . 本身,需要用转意符 \\
regx = ".."; //匹配两个任意字符
regx = "\\|";// | 或者
regx="\\d"; // 等同于[0-9]
regx="\\w"; //等同于[0-9a-z_A-Z]
regx="a*"; //0次或多次
regx="[a-z]?";// ? 0次或一次
regx="[a-zA-Z0-9]+"; //+ 一次或多次
regx="[a-z]{5}";//正好n次
regx="[a-z]{2,}"; //不能少于2次
regx="[0-9]{5,9}"; //大于等于5 小于等于 9
boolean matches = "abc".matches(regx);// 用来判断你这个字符串,符不符合我传入的这个正则表达式
boolean b = "123232".matches(regx);
System.out.println(b);
System.out.println(matches);
//1:要求必须是5 - 15 位数字
//2:0 不能开头
String strRgex = "[1-9][0-9]{4,14}";
校验QQ号码:
//需求:校验qq号码.
//1:要求必须是5 - 15 位数字
//2:0 不能开头
//定义一个正则表达式
String strRgex="[1-9][0-9]{4,14}";
正则表达式的分割功能
普通的字符串分割:
String str="username=张三=password=123456";
String[] split = str.split("=");
System.out.println(split[0]);
System.out.println(split[1]);
System.out.println(split[2]);
System.out.println(split[3]);
/*结果
username
张三
password
123456*/
使用正则表达式规则分割:
String str2 = "asdfasfd212121asfdasdfaiefdfas313232323adsfasfasfdasdf";
String strRegx="[0-9]+";
String[] split2 = str2.split(strRegx);
System.out.println(Arrays.toString(split2));
System.out.println(split2[0]);
System.out.println(split2[1]);
System.out.println(split2[2]);
/*
[asdfasfd, asfdasdfaiefdfas, adsfasfasfdasdf]
asdfasfd
asfdasdfaiefdfas
adsfasfasfdasdf
*/
正则表达式的替换功能
普通替换
String s = "奥巴马和克林顿是好朋友".replace("奥巴马", "*").replace("克林顿", "*");
System.out.println(s);
//结果:*和*是好朋友
正则表达式的替换
String string="12321312asdfasdfasdf1323123123123asdfasdfasfd1312312312";
//replaceAll("[0-9]+", ""); 根据正则表达式去替换
String s1 = string.replaceAll("[0-9]+", "");
System.out.println(s1);
//结果:asdfasdfasdfasdfasdfasfd
模式器,匹配器
Pattern模式器 用来封装一个正则表达式
Matcher匹配器 可以封装一个待匹配的数据
可以通过匹配器中的方法,进行匹配
//获取一个模式器
Pattern p = Pattern.compile("a*b*");
//通过模式器获取一个匹配器
Matcher m = p.matcher("aaaaab");
//进行匹配
boolean b = m.matches();
System.out.println(b);
//如果说你只是想看一个字符串,符不符合一个正则表达式的规则
//那么你就使用字符串类中的matches()的方法
boolean matches = "aaaaab".matches("a*b*");
System.out.println(matches);
案例演示:
// da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?
//把下面这个字符串中是三个字母组成的单词,获取出来
String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
//boolean find ()
//尝试查找与该模式匹配的输入序列的下一个子序列。
//String group ()
//返回由以前匹配操作所匹配的输入子序列。
String strRegx="\\b[a-z]{3}\\b";
//把正则表达式封装到模式器中
Pattern p = Pattern.compile(strRegx);
//获取匹配器,把待匹配的字符串传进去
Matcher matcher = p.matcher(str);
boolean b = matcher.find();
while (matcher.find()){
String group = matcher.group();
System.out.println(group);
}
/* 结果:jin
yao
xia
wan
gao*/