How to use regex lookahead and match the previous string / character class

℡╲_俬逩灬. 提交于 2021-02-05 07:56:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!