Regex to match string not ending with pattern

后端 未结 4 1495
北恋
北恋 2020-12-06 11:07

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,}$

相关标签:
4条回答
  • 2020-12-06 11:46

    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.

    0 讨论(0)
  • 2020-12-06 11:51

    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.

    0 讨论(0)
  • 2020-12-06 12:06

    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
    
    0 讨论(0)
  • 2020-12-06 12:06

    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}$
    
    0 讨论(0)
提交回复
热议问题