简体   繁体   中英

python if list_item == re.match

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    

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
  1. don't use a try catch without actually doing nothing, it would just hide the error.
  2. match() doesn't return a string but a match object, can't use the == operator, but the return will be None if no match are foun so for a quick fix you can write it as:
if re.match(r'\d\d1', item) is not None
  1. you can use [] to specify all digit except 1 as [023456789] instead of using the and as in:
if re.match(r'\d[023456789]1', item) is not None:
  1. matchall() seems more fititng here, give it a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM