简体   繁体   English

正则表达式定义常规语言

[英]Regular Expression to define a Regular Language

I need to write a regular expression for a regular language which its strings always start with 1 and have even number of 0s. 我需要为常规语言编写正则表达式,其字符串始终以1开头,偶数为0。

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. 我已经在Java中尝试了^ 1 +(00)+(1 | 00)*并且它接受了100,1100100,10011001等字符串,但是当0的数量是偶数时它不接受10101010。 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. 根据您尝试的正则表达式,我假设只允许0和1。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM