参考博客:http://blog.csdn.net/libingxin/article/details/7840998
?=
正向向前查找:出现在指定项之后的字符序列不会被正则表达式引擎返回
?<=
正向向后查找:出现在指定项之前的字符序列不会被正则表达式引擎返回
?<!
负向向后查找:不出现在指定项之前的字符序列不会被正则表达式引擎返回
?!
负向向前查找:不出现在指定项之后的字符序列不会被正则表达式引擎返回
记忆:= 为正向 有<表示向后,没有<表示向前, !表示负向
@Test
public void look(){
String str="\\http://www.baidu.com";
System.out.println("?= 正向向前查找");
String prex=".+(?=:)";
Pattern p=Pattern.compile(prex);
Matcher m=p.matcher(str);
while(m.find()){
System.out.println(m.group()); //\http
}
/**可以看到字表达式(?=:)匹配:,
但被匹配的:没有出现在最终的匹配结果里,
我们用?=向正则表达式引擎表明:只要找到:就行了,
不要把它包括在最终结果里。用术语来说,就是”不消费”它。*/
System.out.println("?<= 正向向后查找 ");
String str2="d23.90 d12.32 d12.34 33.33";
String prex2="(?<=d)[0-9].+"; // 23.90 d12.32 d12.34 33.33
//String prex2="(?<=d)[0-9].+?"; //result :23 12 12
p=Pattern.compile(prex2);
m=p.matcher(str2);
while(m.find()){
System.out.println(m.group());
}
System.out.println("?! 负向前查找 ");
String str3="the book cost and the phone cost 1000 2d";
String prex3="\\d+(?!d)"; //1000
/**String prex3="\\d+(?=d)"; //result :2 ?=d 表示d这个字母遇见了就行了
* 解析:是以空格分隔解析的,所以2d 才满足这个正则表达式
* 也就输出2了
*/
p=Pattern.compile(prex3);
m=p.matcher(str3);
while(m.find()){
System.out.println(m.group());
}
System.out.println("?<!负向后查找 ");
String str4="the d2 wow 30";
String prex4="(?<!d)\\d+";
//String prex4=
p=Pattern.compile(prex4);
m=p.matcher(str4);
while(m.find()){
System.out.println(m.group());
}
System.out.println("向前查找向后查找混合使用 ");
String str5="(title)ben hah wowo(/title)";
String prex5="(?<=(title)).*(?=(/title))"; //result :)ben hah wowo(
/**
* 我理解的是result没有那两个半括号 但是就是有 这是为什么
*/
//String prex5=
p=Pattern.compile(prex5);
m=p.matcher(str5);
while(m.find()){
System.out.println(m.group());
}
}