匹配电话号码
匹配成功后,如果提取想要的字符串
使用(...)可以分组:"^(\d{3,4})\-(\d{6,8})$"
String.matcher vs Pattern.matcher
public static void main(String[] args){
String regex = "^\\d{3,4}\\-\\d{6,8}";
System.out.println("010-123456789".matches(regex));
Pattern pattern = Pattern.compile("^(\\d{3,4})\\-(\\d{6,8})$");
Matcher matcher = pattern.matcher("010-12345678");
System.out.println(matcher.matches());
System.out.println(matcher.group(1)+"\t"+matcher.group(2));
}
反复使用一个正则表达式字符串进行快速匹配效率较低:
- 正则表达式虽然是一个字符串,但首先要编译为Pattern对象 ,然后再进行匹配。因此可以先创建Pattern对象,然后反复使用
public static void main(String[] args){
Pattern pattern = Pattern.compile("^(\\d{3,4})\\-(\\d{6,8})$");
//获取匹配结果
System.out.println(pattern.matcher("010-12345678").matches());
System.out.println(pattern.matcher("021-123456").matches());
System.out.println(pattern.matcher("022#1234567").matches());
//获取matcher对象,在获取匹配结果
Matcher matcher = pattern.matcher("010-1234567");
System.out.println(matcher.matches());
}
}
使用Matcher.group(n)可以快速提取字串
public static void main(String[] args) throws IllegalAccessException {
Pattern pattern = Pattern.compile("^(\\d{3,4})\\-(\\d{6,8})$");
//获取matcher对象
Matcher matcher = pattern.matcher("010-1234567");
//必须匹配成功,才能提取子串,即matcher.matches()不能省略,否则会报java.lang.IllegalStateException,
try{
System.out.println(matcher.group(0));
}catch (Exception e){
System.out.println(e.getClass()+": "+e.getMessage());
}
//因此可以改写为
if (matcher.matches()) {
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
总结:
正则表达式分组可以通过Matcher对象快速提取字串:
group(0)
group(1)
group(2)
...
原文地址:https://www.cnblogs.com/csj2018/p/10754354.html
时间: 2024-10-03 22:41:51