[Solved] Regex to match string not ending with pattern

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:


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

Enquirer: Jelena


Solution #1:

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


Otherwise, use hsz’s answer.


^          # 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
Respondent: Tim Pietzcker

Solution #2:

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



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.

Respondent: hsz

Solution #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.

Respondent: jnm2

Solution #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.


which simplifies to


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.

Respondent: Nathan MacInnes

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.