【发布时间】:2010-07-15 20:41:34
【问题描述】:
我需要用简单的通配符匹配两个字符串:
"oh.my.*" 匹配 "*.my.life"、"oh.my.goodness" 和 "*.*.*",但不匹配 "in.my.house"
唯一的通配符是 *,它替换任何字符的字符串(减号。)
我想过使用 fnmatch,但它不接受文件名中的通配符。
我现在正在使用一些带有正则表达式的代码 - 我想更简单的东西会更好:
def notify(self, event, message):
events = []
r = re.compile(event.replace('.','\.').replace('*','[^\.]+'))
for e in self._events:
if r.match(e):
events.append(e)
else:
if e.find('*')>-1:
r2 = re.compile(e.replace('.','\.').replace('*','[^\.]+'))
if r2.match(event):
events.append(e)
for event in events:
for callback in self._events[event]:
callback(self, message)
【问题讨论】:
-
应该
oh.*匹配oh.my.goodness还是*不能匹配点?在您的所有示例中,点的数量始终相同。 -
* 无法完全匹配点。
-
@ts:哦,现在我看到你已经在你的问题中提到了,我只是在第一次阅读时错过了它。