Skip to main content
 首页 » 编程设计

python之查找关键字符之间的单词模式

2025年05月04日9leader

尝试创建正则表达式来查找一个长字符串中的关键字,并且当关键字没有被字母包围时。如果字符串被破折号或下划线包围,只要它不被字母包围。只需要找到一个出现的词,才算匹配。只关心在一个长字符串中找到它。目前,当单词旁边有一个“_”时,我无法让它变为 True。有更好的表达方式吗?

编辑 - 我发现了一个案例,我需要它是真实的并且没有将它添加到示例中。

import re 
 
key_words = ['go', 'at', 'why', 'stop' ] 
 
false_match = ['going_get_that', 'that_is_wstop', 'whysper','stoping_tat' ] 
 
positive_match = ['go-around', 'go_at_going','stop-by_the_store', 'stop','something-stop', 'something_stop'] 
pattern = r"\b(%s)\b" % '|'.join(key_words) 
 
for word in false_match + positive_match: 
    if re.match(pattern,word): 
         print True, word 
    else: 
         print False, word 

当前输出:

False going_get_that 
False that_is_wstop 
False whysper 
False stoping_tat 
True go-around 
False go_at_going 
True stop-by_the_store 
True stop 

编辑 - 这需要为真

  False something-stop 
  False something_stop 

期望的输出:

    False going_get_that 
    False that_is_wstop 
    False whysper 
    False stoping_tat 
    True go-around 
    True go_at_going 
    True stop-by_the_store 
    True stop 
    True something-stop 
    True something_stop 

请您参考如下方法:

使用消极的目光(向前|向后):

import re 
 
key_words = ['go', 'at', 'why', 'stop' ] 
 
false_match = ['going_get_that', 'that_is_wstop', 'whysper','stoping_tat' ] 
 
positive_match = ['go-around', 'go_at_going','stop-by_the_store', 'stop', 'something-stop', 'something_stop'] 
pattern = r"(?<![a-zA-Z])(%s)(?![a-zA-Z])" % '|'.join(key_words) 
 
for word in false_match + positive_match: 
    if re.search(pattern,word): 
         print True, word 
    else: 
         print False, word