简体   繁体   中英

match with any of the list items and break on first match

I am very new to python and to programming in general. I am trying to match the words in a file to any one of the items in a list and once a match is found return true. My code does not break on the first match even if use break for the match. Please excuse for any obvious mistakes and bad coding style.

strings = ["string1", "string2", "string3", "string4"]
node_file = open(filename, 'r')

##printing to check for first match
for line in node_file:
    words = line.split(" ")
    for w in words:
        for string in strings:
            if re.match(string,w):
                print 'found match' , w
                break 

break only applies to the innermost loop it is executed in; if you want to break out on any of the enclosing loops, you'll need some extra mechanism. For example, to break out of all of them, you could put this in a function & use return to exit the function. Another approach would be to have some variable, say done , which gets set when you want to break, and have each enclosing loop check it to see if it needs to break.

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