Regex to match string not ending with pattern

痞子三分冷 提交于 2019-11-26 21:35:31

问题


I try to find a regex that matches the string only if the string does not end with at least three '0' or more. Intuitively, I tried:

.*[^0]{3,}$

But this does not match when there one or two zeroes at the end of the string.


回答1:


If you have to do it without lookbehind assertions (i. e. in JavaScript):

^(?:.{0,2}|.*(?!000).{3})$

Otherwise, use hsz's answer.

Explanation:

^          # Start of string
(?:        # Either match...
 .{0,2}    #  a string of up to two characters
|          # or
 .*        #  any string
 (?!000)   #   (unless followed by three zeroes)
 .{3}      #  followed by three characters
)          # End of alternation
$          # End of string



回答2:


You can try using a negative look-behind, i.e.:

(?<!000)$

Tests:

Test  Target String   Matches
1     654153640       Yes
2     5646549800      Yes   
3     848461158000    No
4     84681840000     No
5     35450008748     Yes   

Please keep in mind that negative look-behinds aren't supported in every language, however.




回答3:


What wrong with the no-look-behind, more general-purpose ^(.(?!.*0{3,}$))*$?

The general pattern is ^(.(?!.* + not-ending-with-pattern + $))*$. You don't have to reverse engineer the state machine like Tim's answer does; you just insert the pattern you don't want to match at the end.




回答4:


This is one of those things that RegExes aren't that great at, because the string isn't very regular (whatever that means). The only way I could come up with was to give it every possibility.

.*[^0]..$|.*.[^0].$|.*..[^0]$

which simplifies to

.*([^0]|[^0].|[^0]..)$

That's fine if you only want strings not ending in three 0s, but strings not ending in ten 0s would be long. But thankfully, this string is a bit more regular than some of these sorts of combinations, and you can simplify it further.

.*[^0].{0,2}$


来源:https://stackoverflow.com/questions/11431295/regex-to-match-string-not-ending-with-pattern

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