简体   繁体   English

检查项目是否与正则表达式字符串匹配

[英]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). 基本上,我的目的是检查message任何部分是否在matches任何项目内,但是使用此脚本,它始终返回False (不匹配)。

Could someone point out if I am doing something wrong in this code? 有人可以指出我在这段代码中做错了什么吗?

Use search rather than match . 使用search而不是match As an optimization, match only starts looking at the beginning of the string, rather than anywhere in it . 作为一种优化, match只开始于字符串的开头,而不是字符串中的任何地方

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 : 请注意,如果您只关心子字符串并且不需要在正则表达式上进行匹配,则只需使用in运算符

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

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: 如icktoofay的回答所示,如果要搜索字符串中的任何位置,则应使用re.search()而不是re.match() ,但是对于这种简单的操作,可以使用常规的子字符串测试:

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

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

print process(message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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