问题
Trying to use negative look ahead to match a number if it doesn't precede a % sign.
\d+(?!%) .8989% .
//matches 898, but not the 9% .
I'd like it to match 8989 as a whole.
Also is it possible use negative look ahead with matching a whole character class or more complex regex?[\d.+](?!%) .\d+(\.\d{1,2})?(?!%) .
Which would match decimals not preceding a %
回答1:
The \d+(?!%) pattern matches one or more digits, and grabs 8989 in 8989% at first, but the (?!%) negative lookahead fails that match, and the engine, seeing the + quantifier, starts backtracking. It discards the last 9 from the match buffer and retries the (?!%) lookahead that succeeds as 898 is not followed with % symbol.
You may use
/\d+(?![\d%])/g
See the regex demo
The (?![\d%]) negative lookahead will fail the match if 1+ digits is followed with any digit or % char, and thus will not return partial matches of 1+ digits that are followed with a % symbol.
来源:https://stackoverflow.com/questions/52469613/how-to-use-regex-lookahead-and-match-the-previous-string-character-class