1. 正向前查找(positive lookahead)

正则表达式:q(?=u)u

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

源文本:quit

结果:qu

解释:Let's take one more look inside, to make sure you understand the implications of the lookahead. Let's apply q(?=u)to quit. The lookahead is now positive and is followed by another token. Again, q matches q and u matches u. Again, the match from the lookahead must be discarded, so the engine steps back from i in the string to u. The lookahead was successful, so the engine continues with i. But i cannot match u. So this match attempt fails. All remaining attempts fail as well, because there are no more q's in the string.

备注:为了匹配成功,将表达式 q(?=u)改为 q(?=u)u 

2. 正向后查找(positive lookbehind)

正则表达式:u(?<=u)i

源文本:quit

结果:ui

解释:Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. 首先找到u,下一个字符是i,然后引擎向回查找一个字符,与向后查找匹配,再继续与下一个字符i匹配成功。(参考段落:More Regex Engine Internals)

3. 负向前查找(negative lookahead)

正则表达式:(?<!a)b

源文本:bed

结果:b

解释:(?<!a)b matches a "b" that is not preceded by an "a", using negative lookbehind. It doesn't match cab, but matches the b (and only the b) in bed or debt. (?<=a)b (positive lookbehind) matches the b (and only the b) in cab, but does not match bed or debt.

4. 负向后查找(negative lookbehind)

正则表达式:\b\w+(?<!s)\b

源文本:john's

结果:john

解释:\b\w+\b的结果为john和s,(?<!s)去掉了s。

 

参考:https://www.regular-expressions.info/lookaround.html

 

应用:

1. 密码复杂度要求:长度8位以上,由数字,字母,特殊字符组成。

正则表达式:^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[_,!@#$%^&*()<>-])[0-9A-Za-z_,!@#$%^&*()<>-]{8,20}$

2.密码复杂度要求:长度6位以上,由数字,字母,特殊字符中的二者组成。

正则表达式:^(?![0-9]+$)(?![a-zA-Z]+$)(?![_,!@#$%^&*()<>-]+$)[0-9A-Za-z_,!@#$%^&*()<>-]{6,20}$

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄