关于正则表达式的具体内容,在上一篇博文中已经具体介绍了,本博文具体介绍Java中的正则表达式使用方法
在Java中,主要通过Pattern类和Matcher类来使用。
首先,调用compile方法,如
Pattern p = Pattern.compile(exp);
然后创建匹配对象
Matcher m = p.matcher(String);
举例如下
public static void main(String[] args){
//表达式对象
Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
//创建matcher对象
Matcher m = p.matcher("aa22**fda21*feda123 ");
while(m.find()){
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
}
}
结果为
aa22
aa
22
fda21
fda
21
feda123
feda
123
Matcher.find 是扫描输入的序列,并查找与该模式匹配的子序列
m.group()或者m.group(0) 返回整个匹配到的字符串
m.group(i) 返回第i个捕获组内容
另外一种正则表达式使用场景:String.split(exp)
public static void main(String[] args){
//表达式对象
String str = "fd42389afds2fd1fd";
String[] arry = str.split("\\d+");
System.out.println(Arrays.toString(arry));
}
结果是:
[fd, afds, fd, fd]