Home > Net >  python if list_item == re.match
python if list_item == re.match

Time:01-31

I'm trying to practice regex patterns with conditions in python (googlecollab), but stuck in (if... and...) by getting proper numbers from the list[000 to 999] - i need only numbers, ending with one digit '1' (not 11, 111, 211 - I need only 001, 021, 031, 101), but it returns nothing with multiple condition... if I clear code starting with 'and' in condition - it returns all ones, elevens, hundred elevens...

list_ = []
list_.append('000')
for a in range(999):
    list_.append(str(a 1))

for i, el in  enumerate(list_):
    if len(el) == 1:
        list_[i] = '00' el
    elif len(el) == 2:
        list_[i] = '0' el

for item in list_:
    try:
        if item == re.match(r'\d\d1', item).group() \
        and item != re.match(r'\d11', item).group():
            print(item) 
    except:
        pass    

CodePudding user response:

To match only "numbers" which end with one(not more) digit 1 use the following regex pattern:

for i in list_:
    m = re.match(r'\d(0|[2-9])1$', i)
    if m:
        print(i)

  • (0|[2-9]) - alternation group: to match either 0 or any in range 2-9
  • Related