正则表达式零宽断言

下面是零宽断言的几个例子:

$str = 'by ttabdef';
 
//1、(?:exp) 匹配exp但是不捕获
preg_match('/(?:ab)def/', $str, $match1);/*array([0] => abdef)*/
 
//2、(?=exp)断言自身出现的位置的后面能匹配表达式exp
$str1 = 'dancing';
preg_match('/\w+(?=ing)/', $str1, $t1);//array([0] => danc)
preg_match('/tt(?=ab)ab/', $str, $match2);//Array([0] => ttab)
 
//3、(?<=exp)断言自身出现位置的前面能匹配正则表达式, js不支持该写法
preg_match('/(?<=ab)def/', $str, $match3);//array([0] => def)
preg_match('/(?<=c)def/', $str, $t2);//array()
 
//4、(?!exp)断言自身出现位置的后面不能匹配正则表达式
preg_match('/tt(?!c)/', $str, $match4);//array([0] => tt)
 
//5、(?<!exp)断言自身出现位置的前面不能匹配正则表达式, js不支持该写法
preg_match('/(?<!c)def/', $str, $t3);//array([0] => def)

在提数时会遇到这种情况:

原sql中:keyword != "http://css.cn.msn.com/msntoday/default.html"  and
        keyword != "http://css.cn.msn.com/msntoday/dictoday/default.shtml" and
        keyword != "http://css.cn.msn.com/msntoday/default_dict.html"

正则写的话,就用到负向零宽断言,如下:

$regex = '/(?<!css.cn.msn.com/msntoday/(default|dictoday/default|default_dict)\\.[s]?html$/i'

但是有一点需要注意, 逆序环视只能匹配固定长度的文本 。不可以使用 (?<=books?) 、 (?<=\w+)  或 (?=\d{2,3})
提数时也会遇到如下情况:


1
原sql中:(keyword like "%.html" or keyword like "%.shtml") and  (keyword NOT LIKE "%.ynet.com%")

但是不能用如下正则:

$regex = '/(?<!ynet.com).*[s]?html/i'


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值