Skip to main content
 首页 » 编程设计

python之使用正则表达式查找具有条件的子字符串

2025年01月19日23yyy_WW

我想返回 False只有当子字符串前后都有字母时:

例如给定目标 'at' 和

strings = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it'] 

我想返回 [True, True, True, False]。

我现在:

def foo(p,i): 
    if p.findall(i): 
        return True 
    return False 
 
pat = re.compile(r'\bat\b') 
[foo(pat,i) for i in strings] 

返回 [True, False, False, False]。

请您参考如下方法:

您可以使用 re.search 而不是 re.findall 因为您只测试一个字符串 一场比赛。

如果你只需要匹配ASCII,单词两边的[a-zA-Z]就可以了。

使用

import re 
strs = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it'] 
 
def foo(p,i): 
    return False if p.search(i) else True 
 
word = 'at' 
pat = re.compile(r'[a-zA-Z]{}[a-zA-Z]'.format(word)) 
print([foo(pat,i) for i in strs]) 
# => [True, True, True, False] 

参见 Python demo

如果您打算使用 Unicode 字母,请将 [a-zA-Z] 替换为 [^\W\d_]。在 Python 3 中,默认使用 re.U,在 Python 2 中,您需要添加它。