使用正则表达式匹配奇数为0、偶数为1的二进制字符串

2024-05-15 05:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

[修订信息]

一些有效输入

  • 101
  • 10001
  • 00011
  • 11000
  • 0

一些无效输入

  • 十一,
  • 00
  • 10101
  • 101111

编辑: 对于那些认为ReGeX不是解决问题的方法的人来说,这是绝对正确的,但是对于这个问题,我需要使用ReGeX。 此外,我对simpler的定义是减少正则表达式中的字符数(最小长度约为22个字符)


Tags: 方法信息编辑定义字符regex解决问题simpler
3条回答

使用来自collectionsCounter是另一种方法。它可以很容易地查找奇偶序列,并确保字符串只有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

如果你决定用正则表达式来做这件事,那么对于“simplify”的某些定义,这可能是合适的

(?=^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

Demo

相关问题 更多 >

    热门问题