Markum
Markum

Reputation: 4049

Check if an item matches a regex string

I'm using this script:

import re

message = 'oh, hey there'
matches = ['hi', 'hey', 'hello']

def process(message):
    for item in matches:
        search = re.match(item, message)

    if search == None:
        return False
    return True

print process(message)

Basically, my aim is to check if any part of the message is inside any of the items in matches, however using this script, it always returns False (no match).

Could someone point out if I am doing something wrong in this code?

Upvotes: 0

Views: 122

Answers (2)

icktoofay
icktoofay

Reputation: 129001

Use search rather than match. As an optimization, match only starts looking at the beginning of the string, rather than anywhere in it.

Additionally, you're only looking at the result of the last match attempt. You should check inside of the loop and return early if any match:

for item in matches:
    if re.search(item, message):
        return True
return False

Note that if you only care about substrings and don't need to match on regular expressions, just use the in operator:

for item in matches:
    if item in message:
        return True
return False

Upvotes: 3

Andrew Clark
Andrew Clark

Reputation: 208485

As icktoofay's answer indicates, you should be using re.search() instead of re.match() if you want to search anywhere in the string, however for something this simple you could use a normal substring test:

message = 'oh, hey there'
matches = ['hi', 'hey', 'hello']

def process(message):
    return any(item in message for item in matches)

print process(message)

Upvotes: 2

Related Questions