正则表达式相邻字符

时间:2012-08-13 13:03:35

标签: python regex regex-negation

我正在尝试制定一个正则表达式(在Python中运行),它传递一个单词并且只需要找到不包含2个相邻元音的单词。例如:

me - would match
mee - would not match
meat - would not match
base - would match
basketball - would match

我迷失在这里,因为我不知道如何检查不存在的东西?

感谢您的帮助

2 个答案:

答案 0 :(得分:4)

import re

r = re.compile("[aeiou][aeiou]")
m = r.search("me")   # => None
m = r.search("mee")  # => Matcher
m = r.search("meat") # => Matcher
m = r.search("base") # => None

所有不匹配的案例if not mTrue

答案 1 :(得分:3)

m = re.match(r"(?:[^euioa]|[euioa](?![euioa]))*$", word)

@Tichodroma's answer更简单,因此如果您可以稍后在代码中否定匹配,那么应该更好一点,即只需写if not m,您可以使用此解决方案编写if m

相关问题