Home > database >  Regular expression of a string ending in even number of zeros?
Regular expression of a string ending in even number of zeros?

Time:09-20

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.

CodePudding user response:

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

CodePudding user response:

Guess, you need to change (1*0*1*)* in your current formula to (0*1)* resulting in

^(?:0*1)*(?:00) $

See this demo at regex101

I further anchored the pattern and used (?: non capturing groups ) for repitition.

  • Related