一:作用
用于操作字符串数据
二:特殊符号的作用(元字符)
1 字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)
[a-z&&[def]] d、e 或 f(交集)
[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](减去)
[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](减去)
2 字符
x 字符 x
\\ 反斜线字符
3 预定义字符类
. 任何字符(与行结束符可能匹配也可能不匹配)
\d 数字:[0-9]
\D 非数字: [^0-9]
\s 空白字符:[ \t\n\x0B\f\r]
\S 非空白字符:[^\s]
\w 单词字符:[a-zA-Z_0-9]
\W 非单词字符:[^\w]
4 Greedy 数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次
5 边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界
\B 非单词边界
\A 输入的开头
\G 上一个匹配的结尾
\Z 输入的结尾,仅用于最后的结束符(如果有的话)
\z 输入的结尾
三:使用正则
使用正则表达式验证手机号
String tel = "15800001111";
1 、创建正则模式
rex 代表 开头 为1 第二位是3或5或8 加上 9位数字
调用抽象方法 pattern的 complie方法 创建一个正则模式
String rex = "1[358]\\d{9}";
Pattern pat = Pattern.compile(rex);
2、 使用这个正则模式
Matcher 的 find 方法,验证。这个正则表达式是否匹配当前字符串
Pattern pat = Pattern.compile(rex);
Matcher ma = pat.matcher(tel);
System.out.println(ma.find());
全部代码
public static void main(String[] args){
String tel = "15800001111";
String rex = "1[358]\\d{9}";
Pattern pat = Pattern.compile(rex);
Matcher ma = pat.matcher(tel);
System.out.println(ma.find());
}
3、使用正则查询字符串中的某些东西
查询字符串中所有的 长度为三的子串
String str = "da jia hao,ming tian bu fang jia!";
创建好模式。并使用则正模式
String str = "da jia hao,ming tian bu fang jia!";
String rex = "\\w{3}";
Pattern pat = Pattern.compile(rex);
查询到的结果肯定不唯一。
Matcher 可以当成 一个 已经使用过正则后得到的一个 “结果集”
find()查询该结果集中的下一个位置是否有结果
group()返回该位置的结果
while(ma.find()){
System.out.println(ma.group());
}
四:正则中的元组
把刚刚的查询字符串换一个
String str = "da jia2 hao5,ming6 tian7 bu5 fang1 jia3!";
现在需要查询到的东西不只是长度为3的子串
还包括子串后紧跟的数字
使用元组
元组就是()括号,代表我将要获取到的结果会是两个。
String rex = "(\\w{3})(\\d)";
塞入正则模式
String rex = "(\\w{3})(\\d)";
Pattern pat = Pattern.compile(rex);
Matcher ma = pat.matcher(str);
查询:
查询每个字符串
while(ma.find()){
System.out.println(ma.group(1));
}
查询每个字符串后面的数字
while(ma.find()){
System.out.println(ma.group(2));
}
group()带参数
group() 不带参数或者 group(0) 都代表获取整个正则匹配到的结果
group(1)第一个元组中的结果
group(2)第二个元组中的结果
元组:想要在匹配时获取更加细化的数据时使用
五:String的直接使用
String 中有很多内置方法可以直接使用正则表达式。
效果:简洁快速。
1、替换
把字符串中的 . 替换成 空格
String str = ".1...2.....3....";
str.replace(oldChar, newChar) 使用 特定字符串替换特定字符串
str = str.replace("."," ");
System.out.println(str);
str.replaceAll(regex, replacement)
使用
正则
表达式 替换成特定字符串
点“.” 在正则中属于 有特别意义的字符。代表所有非换行的字符
需要转译
str = str.replaceAll("\\."," ");
System.out.println(str);
2.替换2
将连续的字符替换成一个
String str = "我我我我我我我要要要要要要要要要学学学学学学学编编编编编编编程程程程程程程";
str = str.replaceAll("(.)\\1+","$1");
System.out.println(str);
3、切割字符串
把每个字装进数组里。使用 “-” 分割他们
String str = "我-要-学-编-程";
String[] rex = str.split("-");
System.out.println(rex[0]);