문제

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?

도움이 되었습니까?

해결책

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]*)*$"

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top