正则表达式(regex):是使用字符串来描述、匹配一系列符合某个句法规则的字符串
用途:匹配、切割、替换、获取字符串
正则表达式由一些普通字符和一些元字符组成
常见元字符:
Java中“\”有不同的用法,\n时它为转义字符,在正则表达式中又用于组成元字符,那么"\"到底都有哪些含义?
1)反斜线后面可以加特定字符,组成“转义字符”,例如:\n,\t
2)用于取消元字符的意义,使元字符变为普通字符,例如:“\\”代表普通字符"\"
3)用于组成正则表达式中的元字符,例如:\w在正则表达式中代表一个包含下划线的任何单个字符
Pattern类和Matcher类
Pattern类的对象代表正则表达式编译之后的对象;
Matcher类主要用于执行验证
Pattern类的主要方法:
public static Pattern compile(String regex):将正则表达式封装到Pattern对象中
public Matcher matcher(CharSequence input):返回一个匹配器Matcher,该Matcher对象可以根据正则表达式判断传入的字符串是否符合要求
Matcher类的主要方法:
publicboolean matchers():判断是否匹配成功。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailRegex {
public static void main(String[] args) {
String emailRegex="\\w+@\\w+\\.\\w+\\.?\\w+";
Scanner scan=new Scanner(System.in);
System.out.print("请输入邮箱:");
String email=scan.next();
Pattern pat=Pattern.compile(emailRegex); // 将正则表达式封装到Pattern对象中
Matcher mat=pat.matcher(email); // 创建一个匹配器Matcher,该Matcher对象可以根据正则表达式判断传入的字符串是否符合要求
if(mat.matches()){
System.out.println("恭喜,邮箱格式正确!");
}else{
System.out.println("对不起,邮箱格式不正确!");
}
}
}
这种判断方法比较麻烦,容易记混,那么我们也可以使用另一种:
String类提供了一些判断正则表达式匹配问题的方法:
1.public boolean matches(String regex):判断字符串是否与给定的正则表达式匹配。
2.public String replaceAll(Stringregex,Stringreplacement):字符串替换
3.public String[] split(String regex):字符串拆分
public class StringRegex {
public static void main(String[] args) {
String str="hello1java22regex333python4444C55555";
if(str.matches("\\w+")){
System.out.println("匹配成功!");
}
System.out.println("替换后的字符串为:"+str.replaceAll("\\d+","#"));
String country="中国|美国|俄罗斯|德国";
String[] array=country.split("\\|");
for(String c:array){
System.out.print(c+" ");
}
}
}
最后说一下正则表达式中的?,有两种作用:
1)重复前面表达式0次或1次
2)在表示次数的元字符后加上?代表取消默认的贪婪匹配模式,变为“非贪婪匹配模式”。
例如:String str="abbb";
str.replaceAll("ab+","#") //贪婪模式匹配 结果为:a#
str.replaceAll("ab+?","#") //非贪婪模式匹配 结果为:a#bb