前言
Regular expression正则表达式,简称RegExp,常规通用的表达式,在多个开发语言中都有它的实现,可以通过正则表达式来快速的检索、匹配、查找、替换字符串中的文本。
简单实例
匹配网址
package com.ichochy.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
String input = "https://ichochy.com";
//正则表达式,(.+)代表一个或多个字符
String regex = "https://.+.com";
Boolean flag = Pattern.matches(regex,input);
System.out.println(flag); //全文匹配返回:true
}
}
Matches 方法
Matcher.matches方法,为整块全匹配,字符串完全匹配返回true。
package com.ichochy.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
String input = "https://ichochy.com";
//正则表达式,(.+)代表一个或多个字符
String regex = "https://.+.com";
Pattern pattern = Pattern.compile(regex);//编译表达式
Matcher matcher = pattern.matcher(input);//匹配表达式
System.out.println(matcher.matches());//全文匹配返回:true
}
}
Find 方法
Matcher.find方法,为查找模式匹配,匹配到就返回true。
package com.ichochy.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
String input = "我的网站是:https://ichochy.com,你知道吗?";
//正则表达式,(.+)代表一个或多个字符
String regex = "https://.+.com";
Pattern pattern = Pattern.compile(regex);//编译表达式
Matcher matcher = pattern.matcher(input);//匹配表达式
System.out.println(matcher.find());//查找匹配返回:true
System.out.println(matcher.matches());//全文匹配返回:false
System.out.println(matcher.find());//再次查找匹配返回:false
matcher.reset();//重置匹配器
System.out.println(matcher.find());//重置查找返回:true
}
}
find方法多次调用,出现结果不相同的问题:
This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
Matcher.find方法第一次查找匹配成功后,如果Matcher没有重置(Matcher.reset()),则从上一次匹配成功位置的后面开始查找,所以会出现,再次匹配不成功,返回false。
Group 分组
正则表达式通过括号分组进行匹配,matcher.group(int group):通过组序号获取匹配信息
package com.ichochy.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
String input = "我的网站是:https://ichochy.com,你知道吗?";
String regex = "(https://)(.+)(.com)";//分组表达式
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()){//查找匹配成功
//匹配的信息:https://ichochy.com
System.out.println(matcher.group().toString());
//groupCount 组数
for (int i = 0; i < matcher.groupCount(); i++) {
//每组匹配的信息,注意:序号是从 1 开始
System.out.println(matcher.group(i+1));
}
}
}
}
正则表达式规则
字符
| 构造 | 匹配 |
|---|---|
| x | 字符 x |
| 反斜线字符 | |


