正则表达式
- 概述:指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串,其实就是用来定义一些规则,去校验数据是否符合所定义的规则
- 正则的一些常用语法
package org.westos.test;
public class Test2 {
public static void main(String[] args) {
//正则相关语法
String regx = "[a,b,c,A,B,C]";//出现集合中的任意一个字符,匹配成功
regx = "[0-9]";//出现任意一个数字字符,匹配成功
regx = "[a-z]";//出现任意一个小写字母字符,匹配成功
regx = "[A-Z]";//出现任意一个大写字母字符,匹配成功
regx = "[0-9a-zA-Z]";//出现任意一个数字或者小写字母或者大写字母字符,匹配成功
regx = "[^A-Z]";//^取反的意思,即除了大写字母,其他字符都可以匹配成功
regx = ".";//匹配单个任意字符
regx = "\\.";//只匹配点本身,\\代表转义
regx = "\\d";//等同于"[0-9]"
regx = "\\w";//等同于"[0-9a-zA-Z]"
regx = "ab?";//?代表一次或者没有
regx = "[a-z]*";//*代表没有或者多次
regx = "[a-z]+";//+代表一次或者多次
regx = "[a-z]{5,}";//至少出现5次任意小写字符
regx = "[a-z]{5}";//正好出现5次任意小写字符
regx = "[a-z]{5,10}";//5<=出现的小写字符个数<=10
}
}
- 正则表达式的判断功能
public boolean matches(String regx):判断是否满足规则,满足返回true,否则返回false
package org.westos.test;
import java.util.Scanner;
//校验键盘录入的邮箱是否符合规则
//规则:6 ~18 个字符,可使用字母、数字、下划线,需以字母开头
public class Test2 {
public static void main(String[] args) {
String emailRegx = "[a-zA-Z]\\w{5,17}@163\\.com";
Scanner sc = new Scanner(System.in);
System.out.println("请输入邮箱:");
String s = sc.nextLine();
boolean matches = s.matches(emailRegx);
if(matches){
System.out.println("符合规则");
}else{
System.out.println("不符合规则");
}
}
}
运行结果:
- 正则表达式的分割功能
public String[] split(String regx):根据正则表达式切割字符串内容,返回一个字符串数组
package org.westos.test;
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
String str = "张三dasfew1234李四fdsafn2356王五";
//根据传入的正则切割,将三个人名切割
String[] name = str.split("\\w+");
System.out.println(Arrays.toString(name));
}
}
运行结果:
- 正则表达式的替换功能
public String replaceAll(String regx,String replacement):根据正则表达式代替所以符合规则的元素
package org.westos.test;
public class Test2 {
public static void main(String[] args) {
String str = "a发电部覅b发我就哦服务c废物废物id分为氛围胡ef分为氛围g";
//根据正则表达式将中文去掉,即用空串代替
String s = str.replaceAll("[^A-Za-z0-9]+","");
System.out.println(s);
}
}
运行结果:
- 正则表达式的获取功能
实验该功能需要使用Pattern和Matcher类
Pattern:模式器,把正则表达式封装进该类
Matcher:匹配器,调用方法判断传进来的数据是否符合规则
典型的调用顺序:
public static void main(String[] args) {
//封装正则表达式
Pattern p = Pattern.compile("[0-9]*");
//调用模式器的matcher方法,把待匹配数据传进去
Matcher m = p.matcher("123456");
//调用匹配器的matcher方法,判断数据是否符合规则
boolean b = m.matches();
}
练习:需求:获取下面这个字符串中由三个字符组成的单词
da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?*
package org.westos.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String[] args) {
String str = "da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
//定义符合规则的正则表达式
//这里在定义时,应该把空格也算在表达式中,\\b代表空格
String regx = "\\b[a-z]{3}\\b";
//封装正则表达式
Pattern p = Pattern.compile(regx);
//调用模式器的matcher方法,把待匹配数据传进去
Matcher m = p.matcher(str);
//查找这个字符串中有没有符合正则的数据,用到find方法
boolean b = m.find();
//获取符合正则表达式的数据,用到group方法
while(m.find()){
String group = m.group();
System.out.println(group);
}
}
}
运行结果:
这里要注意,在使用find方法和group方法时,一定要先使用find方法先找到,才能用group方法获取
学习正则表达式,主要是学习它的用法,至于正则表达式的式子,较为复杂的直接百度即可