简体   繁体   中英

Using variable in re.match in python

I am trying to create an array of things to match in a description line. So I can ignore them later on in my script. Below is a sample script that I have been working on, on the side.

Basically I am trying to take a bunch of strings and match it against a bunch of other strings.

AKA: asdf or asfs or wrtw in string = true continue with script if not print this.

import re

ignorelist = ['^test', '(.*)set']

def guess(a):
     for ignore in ignorelist:
             if re.match(ignore, a):
                     return('LOSE!')
             else:
                     return('WIN!')

a = raw_input('Take a guess: ')
print guess(a)

Thanks

You have a bit of logic/flow problem.

You test the first term in the list. If it doesn't match, you go to the else and return "WIN!" without testing any of the other terms in the list.

(Also, ignorelist is outside the function.)

[EDIT: I see you edited the question to include regular expressions, so I will edit the answer back to a re context...] Note that you should use re.search instead of re.match if you want to give it actual regex since re.match only matches at the beginning of the line.

There are innumerable ways to change this, depending on how you want your program to work.

I would re-write guess along these lines. (You can also put ignorelist inside the function instead of passing it.):

ignorelist = [r'^test', r'[abc]set']

def guess(a,il):
    for reg in il:
        if re.search(reg,a):
            return "LOSE"
    return "WIN"

a = raw_input()
print guess(a,ignorelist)

In this case, it will loop through each word, exiting if it finds a match, but if it doesn't (completes the loop without returning anything) then it will finally return "WIN" .

I think it would be far better using a single regex, or a set of them if only one would be to big to compile. Something like:

GUESSER = re.compile('|'.join(ignorelist))

def guess(a):
    if GUESSER.search(a):
        return('WIN!')
    else:
        return('LOSE!')

Note: Pattern in "ignorelist" should be enclosed in a pair of parentheses if they use the or "|" operator.

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