“四向处理”指很多正则表达式引擎所支持的正负 Lookahead 和 Lookbehind 功能。
Lookahead: (?=...), (?!...)
Lookbehind: (?<=...), (?<!...)
Lookaround constructs match a location in the text where
the subpattern would match (lookahead), would not match (negative lookahead), would have finished matching (lookbehind), or would not have finished matching (negative lookbehind). For example, foo(?=bar) matches foo in foobar, but not food. Implementations often limit lookbehind constructs to subpatterns with a predetermined length
密码验证是必需四向处理的一个示例。假定在密码限制中,密码必须介于 4 到 8 个字符,且必须至少包含一个数字。为此,您可以仅在匹配中测试 /d,然后使用字符串操作来测试长度。但要在正则表达式中实现这一切,必须使用 Lookahead。特别是正 lookahead,如下所示:^(?=.*/d).{4,8}$
(pattern) 匹配pattern 并获取这一匹配。所获取的匹配可以从产生的Matches 集合得到,在VBScript 中使用 SubMatches 集合,在Visual Basic Scripting Edition 中则使用 $0…$9 属性。要匹配圆括号字符,请使用 ’/(’ 或 ’/)’。
(?:pattern) 匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用 "或" 字符 (|) 来组合一个模式的各个部分是很有用。例如, ’industr(?:y|ies) 就是一个比 ’industry|industries’ 更简略的表达式。
(?=pattern) 正向预查,在任何匹配 pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,’Windows (?=95|98|NT|2000)’ 能匹配"Windows2000"中的"Windows",但不能匹配"Windows3 .1"中"Windows"。
预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?!pattern) 负向预查,在任何不匹配Negative lookahead matches the search string at any point where a string not matching pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如’Windows (?!95|98|NT|2000)’ 能匹配 "Windows 3.1" 中的 "Windows",但不能匹配 "Windows 2000" 中的 "Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始