Question

I need to write a regular expression for a regular language which its strings always start with 1 and have even number of 0s.

I have already tried ^1+(00)+(1|00)* in Java and it does accept strings like 100, 100100 , 10011001.. etc however it doesn't accept 10101010 while the number of 0s is even. any one with a better idea to define the regex, please?

Était-ce utile?

La solution

Try this:

"^1+(01*01*)*$" 

I'm assuming that only 0 and 1 are allowed, based on the regex you tried. If you want to allow other characters:

"^1[^0]*(0[^0]*0[^0]*)*$"

Autres conseils

I need to write a regular expression for a regular language which its strings always start with 1 and have even number of 0s.

This lookahead based regex should work for you:

/^1(?=(([^0]*0){2})*[^0]*$)/

/^1(?=(([^0]*0){2})*[^0]*$)/.test('10'); // false
/^1(?=(([^0]*0){2})*[^0]*$)/.test('1000000'); // true
/^1(?=(([^0]*0){2})*[^0]*$)/.test('000000'); // false
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top