最近使用 PHP 写了一个应用,主要是正则表达式的处理,趁机系统性的学习了相应知识。
这篇文章的写作方式不是讲理论,而是通过具体的例子来了解正则,这样也更有实践性,在此基础上再去看正则表达式的基本概念会更有收获。
禁止分组的捕获
在正则中分组很有用,可以定义子模式,然后可以通过后向引用来引用分组的内容,但是有的时候仅仅想通过分组来进行范围定义,而不想被分组来捕获,通过一个例子就能明白:
$str = "http://";$preg = '/[a-z]+(?=:)/';preg_match($preg,$str,$arr);print_r($arr);(2)"invisible" 分隔符
也叫 “zero-width” 分隔符,参考下面的例子:
$str = ("chinaWorldHello");$preg = "/(?=[A-Z])/";$arr = preg_split($preg,$str);print_r($arr);(3)匹配强密码
instead of specifying the order that things should appear, it's saying that it must appear but we're not worried about the order.
The first grouping is (?=.{8,}). This checks if there are at least 8 characters in the string. The next grouping (?=.[0-9]) means "any alphanumeric character can happen zero or more times, then any digit can happen". So this checks if there is at least one number in the string. But since the string isn't captured, that one digit can appear anywhere in the string. The next groupings (?=.[a-z]) and (?=.[A-Z]) are looking for the lower case and upper case letter accordingly anywhere in the string.
向后查找 ?<=
?<= 表示假如匹配到特定字符,则返回该字符后面的内容。
?= 表示假如匹配到特定字符,则返回该字符前面的内容。
好了,今天的教程就先到这里,有什么问题大家可以留言,我们来讨论下