Regex negative match query

岁酱吖の 提交于 2019-12-07 08:20:11

问题


I've got a regex issue, I'm trying to ignore just the number '41', I want 4, 1, 14 etc to all match.

I've got this [^\b41\b] which is effectively what I want but this also ignores all single iterations of the values 1 and 4.

As an example, this matches "41", but I want it to NOT match: \b41\b


回答1:


Try something like:

\b(?!41\b)(\d+)

The (?!...) construct is a negative lookahead so this means: find a word boundary that is not followed by "41" and capture a sequence of digits after it.




回答2:


You could use a negative look-ahead assertion to exclude 41:

/\b(?!41\b)\d+\b/

This regular expression is to be interpreted as: At any word boundary \b, if it is not followed by 41\b ((?!41\b)), match one or more digits that are followed by a word boundary.

Or the same with a negative look-behind assertion:

/\b\d+\b(?<!\b41)/

This regular expression is to be interpreted as: Match one or more digits that are surrounded by word boundaries, but only if the substring at the end of the match is not preceded by \b41 ((?<!\b41)).

Or can even use just basic syntax:

/\b(\d|[0-35-9]\d|\d[02-9]|\d{3,})\b/

This matches only sequences of digits surrounded by word boundaries of either:

  • one single digit
  • two digits that do not have a 4 at the first position or not a 1 at the second position
  • three or more digits



回答3:


This is similar to the question "Regular expression that doesn’t contain certain string", so I'll repeat my answer from there:

^((?!41).)*$

This will work for an arbitrary string, not just 41. See my response there for an explanation.



来源:https://stackoverflow.com/questions/2516304/regex-negative-match-query

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