Regex to match string not ending with pattern

Jelena picture Jelena · Jul 11, 2012 · Viewed 23k times · Source

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.

Answer

Tim Pietzcker picture Tim Pietzcker · Jul 11, 2012

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