【问题标题】:Check if an item matches a regex string检查项目是否与正则表达式字符串匹配
【发布时间】:2012-05-27 00:39:09
【问题描述】:

我正在使用这个脚本:

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)

基本上,我的目标是检查message 的任何部分是否在matches 中的任何项目内,但是使用此脚本,它总是返回False(不匹配)。

如果我在这段代码中做错了什么,有人可以指出吗?

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    使用search 而不是match。作为优化,match only starts looking at the beginning of the string, rather than anywhere in it

    此外,您只查看最后一次匹配尝试的结果。您应该检查循环内部,如果有任何匹配项,请尽早返回:

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

    请注意,如果您只关心子字符串并且不需要匹配正则表达式,只需使用the in operator

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

    【讨论】:

    • 嗯,改成.search,问题依旧。
    • @Markum:还有一个问题。我已更新我的答案以包含它。
    【解决方案2】:

    正如 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2014-02-20
      • 2014-02-02
      • 1970-01-01
      相关资源
      最近更新 更多