[SOLVED] Regular expression of a string ending in even number of zeros?

Issue

This Content is from Stack Overflow. Question asked by potroast12

I’m having trouble constructing a regular expression that is not empty and ends with an even number of zeros (ex. 10110010000). I was thinking that I could do something like:

(1* 0* 1*)*(00)+

since the beginning digits can be any number of ones or zeros. The problem with this one is that I think I could input 000 or 100100000 and this would work, even though those end in an odd number of zeros. I’m just having trouble eliminating the possibility of this beginning section ending in an odd number of zeros, which would then affect the total number of zeros that the string ends in.



Solution

You want to find a pair of zeros:

00

That may be repeated:

(00)+

At the end of a string:

(00)+$

That is not preceded by a zero:

(?<!0)(00)+$

Demo: regex101


This Question was asked in StackOverflow by potroast12 and Answered by Tibrogargan It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?