微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式零宽断言

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

$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/',$match2);//Array([0] => ttab)
 
//3、(?<=exp)断言自身出现位置的前面能匹配正则表达式, js不支持该写法
preg_match('/(?<=ab)def/',$match3);//array([0] => def)
preg_match('/(?<=c)def/',$t2);//array()
 
//4、(?!exp)断言自身出现位置的后面不能匹配正则表达式
preg_match('/tt(?!c)/',$match4);//array([0] => tt)
 
//5、(?<!exp)断言自身出现位置的前面不能匹配正则表达式, js不支持该写法
preg_match('/(?<!c)def/',$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'

原文地址:https://www.jb51.cc/regex/361867.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐