Python 如何找出匹配的单词?

Python 如何找出匹配的单词?,python,regex,findall,Python,Regex,Findall,我有一个在字符串中查找单词等的模式。这是我的密码: pattern = { "eval\(.*\)", "hello", "my word" } patterns = "|" . join( pattern ) patterns = "(^.*?(" + patterns + ").*?$)" code = code.strip() m = re.findall( patterns, code,

我有一个在字符串中查找单词等的模式。这是我的密码:

    pattern = {
        "eval\(.*\)",
        "hello",
        "my word"
    }

    patterns = "|" . join( pattern )
    patterns = "(^.*?(" + patterns + ").*?$)"

    code = code.strip()

    m = re.findall( patterns, code, re.IGNORECASE|re.MULTILINE|re.UNICODE )

    if m:
        return m

我怎样才能看到找到了这些单词中的哪一个(eval(),hello..)?在php中,我有preg_match_all函数来获取找到的匹配单词。

我不知道这是否是您想要的,但是您的regexp有两个级别的捕获组:

    (^.*?(hello|my word|eval\(.*\)).*?$)
外部组将捕获整行,而内部组将只捕获指定的单词

re.findall
方法返回包含捕获组的元组列表。在您的特殊情况下,这将是:

    [(outer_group, inner_group), (outer_group, inner_group), ...]
要重复此操作,您可以执行以下操作:

    for line, words in m:
        print('line:', line)
        print('words:', words)
或者,要直接访问项目,请执行以下操作:

    line = m[0][0]
    words = m[0][1] 
注意:

如果外部组被删除,或被设置为非捕获,如下所示:

    ^.*?(hello|my word|eval\(.*\)).*?$
还是这个

    (?:^.*?(hello|my word|eval\(.*\)).*?$)
只有一个捕获组。对于这种特定情况,
re.findall
将返回一个匹配项的平面列表(即,只返回单个字符串,而不是元组)

您需要的
匹配
而不是
findall


match.group
将为您提供匹配的整行代码,而
match.group(1)
match.group(2)
将为您提供单词。

否。当它如此简单,我不必要求它。我需要两个信息,像这样:“你好”,匹配“你好,我的朋友”(匹配词的整行)你应该更新你的问题,专门询问第二条信息。
pattern = {
    "eval\(.*\)",
    "hello",
    "my word"
}
patterns = "|" . join( pattern )
patterns = "^.*?(" + patterns + ").*?$"

code = "i say hello to u"

m = re.match( patterns, code, re.IGNORECASE|re.MULTILINE|re.UNICODE )

if m:
    print m.group()  #the line that matched
    print m.group(1) #the word that matched