[英]Regex of binary strings that have at least one 1 and an even number of 0
I want to find a regex binary string expression that has at least one 1 and an even number of 0.我想找到一个至少有一个 1 和偶数个 0 的正则表达式二进制字符串表达式。
For strings that has an even number of 0, I have:对于偶数为 0 的字符串,我有:
1*(01*01*)*
For strings with at least one 1, I have:对于至少有一个 1 的字符串,我有:
0*1(0+1)*
However, I struggle to combine the two together.但是,我很难将两者结合在一起。 Can anyone give me a hint on how to do it?
谁能给我一个关于如何做的提示? thanks!
谢谢!
Without any fancy regex stuff, just ^
start, $
end anchors and |
没有任何花哨的正则表达式,只需
^
start、 $
end锚点和|
pipe , how about pipe ,怎么样
^(00)*(1|01+0)(1*01*0)*1*$
Should be self explanatory.应该是不言自明的。 Play with it at regex101 .
在 regex101 使用它。 Hope I've not overlooked anything:)
希望我没有忽略任何事情:)
If lookarounds are allowed, I could also think of a negative one: ^(??0*$)(::1*01*0)*1*$
如果允许环视,我也可以考虑一个负面的:
^(??0*$)(::1*01*0)*1*$
One option to match an even number of zeroes and at least a single 1 might be using a positive lookahead (?=
(if supported)匹配偶数个零和至少一个 1 的一个选项可能是使用正向前瞻
(?=
(如果支持)
^(?=(?:1*01*01*)+$)0*1[10]*$
^
Start of string ^
字符串开头(?=
Positive lookahead, assert what is on the right is (?=
正向前瞻,断言右边是
(?:1*01*01*)+$
Repeat 1+ times matching two times a zero with optional one's (?:1*01*01*)+$
重复 1+ 次,匹配两次零和可选的)
Close lookahead )
关闭前瞻0*1
Match zere or more times a zero, then match the required one 0*1
匹配零次或多次零,然后匹配所需的一次[10]*
Match 0+ times a zero or one [10]*
匹配 0+ 次零或一$
End of string $
字符串结尾To also match only one's (so without a zero) you could use要也只匹配一个(所以没有零),你可以使用
^(?=(?:(?:1*01*01*)+|1+)$)0*1[10]*$
I'm not sure if I understand your requirements correctly, but if +
should stand for alternation (normally |
), and only *
, +
, and brackets are allowed (as your comment below suggests) then我不确定我是否正确理解了您的要求,但是如果
+
应该代表交替(通常是|
),并且只允许*
、 +
和括号(正如您在下面的评论所示),那么
(1*01*01*)*(11*+011*0)(1*01*01*)*
should work.应该管用。
The idea is that there must exist a 1
such that either left and right from it must be an equal number of 0
s or left and right from it must be an odd number of 0
s: (11*+011*0)
这个想法是必须存在一个
1
,使得它的左右必须是相等数量的0
s,或者它的左右必须是奇数的0
s: (11*+011*0)
Your 0*1(0+1)*
would also match 01
so I believe it doesn't work.您的
0*1(0+1)*
也将匹配01
所以我相信它不起作用。
In either case left and right from such a group there can exist an equal number of 0
s with an arbitrary number 1
s in between: (1*01*01*)*
.在这种组的左右任何一种情况下,都可以存在相等数量的
0
s,其间可以存在任意数量的1
s: (1*01*01*)*
。
In most regex implementations the above regex would be written as在大多数正则表达式实现中,上述正则表达式将写为
^(1*01*01*)*(11*|011*0)(1*01*01*)*$
. ^(1*01*01*)*(11*|011*0)(1*01*01*)*$
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.