是否有正则表达式让我们检查字符串中是否存在多个单词
前任 :
sentence = "hello i am from New York city"
我想检查句子中是否存在“你好”、“来自”和“城市”。
我试过使用
re.compile("hello|from|city")
但没有运气,因为即使找到单个匹配项,它也会返回 true。
你不能交替,因为任何交替的匹配都会满足正则表达式。相反,从字符串的开头使用多个前瞻:
sentence1 = "hello i am from New York city"
sentence2 = "hello i am from New York"
regex = re.compile(r"^(?=.*hello)(?=.*from)(?=.*city)")
print(regex.match(sentence1))
print(regex.match(sentence2))
输出:
<_sre.SRE_Match object; span=(0, 0), match=''>
None
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句