Home > front end >  Regular expression for matching 1 one and a specified number of zeros
Regular expression for matching 1 one and a specified number of zeros

Time:02-25

Im looking for a regex to use in python to match a string of numbers which has one 1 and a specified number of 0's. For example:

001000 This should match as it has exactly one 1 and 5 zeros. 001010 This shouldnt match as it has more than one 1s and less that 5 zeros.

im sure there is an easy way of doing this...

Thanks,

CodePudding user response:

Using re.search and len we can try:

inp = ['001000', '001010']
for i in inp:
    if re.search(r'^0*10*$', i) and len(i) == 6:
        print("MATCH:    "   i)
    else:
        print("NO MATCH: "   i)

This prints:

MATCH:    001000
NO MATCH: 001010

CodePudding user response:

alternative solution could be :

t = "00111001  asdfasdf  ffff"

def l(x, zn = 5): #x = string, zn == zero_number
    def f(x,zn):
        if x.count("0")>zn:return False
        return True
    tmp = x.split()
    tmp = (i for i in tmp if "0" in i)
    return [j for j in tmp if f(j,zn)]

print l(t) --> ['00111001']

  • Related