1

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.

potroast12
  • 55
  • 5

2 Answers2

3

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

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
  • I don't think negative lookbehind is _technically_ regular (in re: the `theory` tag on the question). But it's benign in this case since you can just write `(^|[^0])` – Alex Reinking Sep 19 '22 at 02:33
0

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.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46