[英]Using Regex To match Binary Strings that have an odd number of 0s and even number of 1s
[编辑信息]
一些有效的输入
一些无效的输入
编辑:对于那些认为 ReGeX 不是通往 go 的方法的人来说是绝对正确的,但是对于这个问题,我需要使用正则表达式。 另外,我对更简单的定义是减少正则表达式中的字符数。(最小值约为 22 个字符)
如果您决定使用正则表达式来执行此操作,那么对于“简化”的某些定义,这可能符合要求。
(?=^0*((10*){2})*?$)(?=^1*(01*)((01*){2})*?$)^.*$
(?= ) assert that
^ $ between the start and end of the string
0* (consume leading zeros)
( )*? there appears as many times as necessary
{2} two instances of
(10*) a 1 followed by any number of 0s
(?=^1* ((01*){2})*?$) perform the same check as before
(01*) but require an extra 0 at the start
这依赖于{2}
量词来要求所讨论的数字是 2 的倍数,而不是一次验证字符串,而是对字符串执行 2 次检查:第一次查找偶数个 1,第二次查找查找偶数个 0,再加上一个额外的 0。
使用collections
中的Counter
是另一种方法。 它可以很容易地查找奇数和偶数序列,并确保字符串只有 1 和 0。
from collections import Counter
def is_valid_binary_string(test_string):
c = Counter(test_string)
# Not valid if anything other than 1s and 0s
if set(c.keys()) - {"0", "1"}:
return False
# Valid only if even number of 1s and odd number of 0s
return c["1"] % 2 == 0 and c["0"] % 2 == 1
您不需要regex
。 使用string.count()
并检查响应是奇数还是偶数来实现这一点非常简单。
testcases = ['101', '10001', '00011', '11000', '0', '11', '00', '10101', '101101111']
for string in testcases:
print(string, 'Valid' if string.count('0') % 2 == 1 and string.count('1') % 2 == 0 else 'Invalid')
输出
101 Valid
10001 Valid
00011 Valid
11000 Valid
0 Valid
11 Invalid
00 Invalid
10101 Invalid
101101111 Invalid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.