?=、?<=、?!、?<! 的使用区别:
1. ?=
exp1(?=exp2):查找 exp2 前面的 exp1。
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("life(?= is)");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
2.?<=
(?<=exp2)exp1:查找 exp2 后面的 exp1。
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(?<=is )a fuck");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
3.?!
exp1(?!exp2):查找后面不是 exp2 的 exp1。
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("movie(?! is)");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
4.?<!
(?<!exp2)exp1:查找前面不是 exp2 的 exp1。
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(?<! is)life");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}