python regex用于获取二进制数之一之间的最大零数

时间:2018-03-17 13:58:15

标签: python regex

我需要找出一个用于计算1和二进制数之间的最大零数的正则表达式。我尝试以下方法获得1之间的最大零数。即,如果我的二进制数是110001001它应该返回3,如果我的二进制数是10010000001那么它应该返回6

import re
binaryarray=['110001001','10101001','10100001','10010000001']
p=r'(?<=1)*(0+)(?=1)*(?<=1)*(0+)(?=1)*'
for b in binaryarray:
    match1=re.search(p,b,re.I)
    if match1:
        print (b)
        if (len(match1.group(1)) > len(match1.group(2))):
             print (len(match1.group(1)))
        else:
             print (len(match1.group(2)))
    else:
        print ("no match")

2 个答案:

答案 0 :(得分:2)

IIUC,你可以试试这个

import re
binaryarray=['110001001','10101001','10100001','10010000001', '00', '1']
for b in binaryarray:
    found = re.findall("(?<=1)(0+)1", b)
    if len(found) == 0:     
        print ("no match")
    else:
        print(len(max(found)))
3
2
4
6
no match           
no match

答案 1 :(得分:1)

您可以执行以下操作:

import re
len(max(re.findall("(?:0)+"), b)))  # if b is an element in your list