'Regex for all strings over L={0,1} ending with an even number of 0s

sorry for the novice question by I've looked and can't seem to find a question that addressed this. I want a regex that describes all strings over L={0,1} ending with an even number of 0s. Examples: 00, 0000, 100, 0100, 001100... basically anything starting with 0 or 1 and ending with an even number of 0s

This is what I've got so far: ((0|1)*1)00+ but this doesn't allow me to get 00 since that must be a 1 always. I can't find a way to put as many 0s as I want at the beginning without having to put that 1.

Thanks a lot.



Solution 1:[1]

You could write the pattern as:

^([01]*1)?(00)+$
  • ^ Start of string
  • ( Capture group
    • [01]*1 Match zero or more repetitions of either 0 or 1 followed by matching 1
  • )? Close the group and make it optional using ?
  • (00)+ Match one or more repetitions of 00
  • $ End of string

See a Regex demo.

If supported, you can also use non capture groups (?:

Solution 2:[2]

An even number of 0s is (00)*. It needs to be at the end, so that part of the regex will be (00)*$.

What precedes that even number of 0s? Either nothing or an arbitrary sequence of 0s and 1s ending with a 1. So that's (|[01]*1).

Putting it together, we have:

^(|[01]*1)(00)*$

(I'm assuming extended regex syntax, where (, ), and | don't have to be escaped. Adjust the syntax as needed.)

I have not tested this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2