javascript中语言的正则表达式只支持先行断言(lookhead)和先行否定断言。不支持后行断言和后行断言,目前,有一个提案,这个提案是github一位叫做 Gorkem Yakin, Nozomu Katō的大神提出的,并被ES组织录入标准!
以下是原文:
RegExp Lookbehind Assertions
Authors: Gorkem Yakin, Nozomu Katō
Introduction
Lookarounds are zero-width assertions that match a string without consuming anything. ECMAScript has lookahead assertions that does this in forward direction, but the language is missing a way to do this backward which the lookbehind assertions provide. With lookbehind assertions, one can make sure that a pattern is or isn't preceded by another, e.g. matching a dollar amount without capturing the dollar sign.
High Level API
There are two versions of lookbehind assertions: positive and negative.
Positive lookbehind assertions are denoted as (?<=...)
and they ensure that the pattern contained within precedes the pattern following the assertion. For example, if one wants to match a dollar amount without capturing the dollar sign, /(?<=\$)\d+(\.\d*)?/
can be used, matching '$10.53'
and returning '10.53'
. This, however, wouldn't match €10.53
.
Negative lookbehind assertions are denoted as (?<!...)
and, on the other hand, make sure that the pattern within doesn't precede the pattern following the assertion. For example, /(?<!\$)\d+(?:\.\d*)/
wouldn't match '$10.53'
, but would '€10.53'
.
All regular expression patterns, even unbounded ones, are allowed as part of lookbehind assertions. Therefore