【发布时间】:2018-08-29 02:04:53
【问题描述】:
我想返回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]。
【问题讨论】:
-
试试
(?<=[a-z])at(?=[a-z])或\Bat\B几乎是一样的。 -
你能再解释一下
I want to return FALSE only if the substring has alphabet letter(s) both before AND after it:吗? -
你不用
re.findall,re.search就够了。由于您需要测试匹配,[^\W\d_]at[^\W\d_]正则表达式可以(它甚至可以匹配任何 Unicode 字母)。如果只需要匹配 ASCII,[a-zA-Z]at[a-zA-Z]就可以了。
标签: python regex string python-3.x substring