在Python中匹配正则表达式列表

-4 投票
1 回答
645 浏览
提问于 2025-04-18 05:01

我有一堆正则表达式,像下面这样:

regexes = [   
    re.compile(r"((intrigued)(.*)(air))"),
    re.compile(r"(air|ipadair)(.*)(wishlist|wish)"),
    re.compile(r"(replac(ed|ing|es|.*)(.*)(with)(.*)(air))"),
    re.compile(r"(upgrade)")]
for regex in regexes:
      if regex.search(post):
           print 1
           break

假设我有一长串字符串,我想在每个字符串中查找这些正则表达式,如果有哪个正则表达式匹配上了,就返回1并停止查找。然后对下一个字符串做同样的事情。现在我的这个方法运行得非常慢,请告诉我有没有更好的办法。

谢谢,

1 个回答

2

正如一些评论提到的,这看起来可能不太适合用正则表达式来处理。我觉得值得看看你到底想做什么。我们先看看其中一个正则表达式:

"(air|ipadair)(.*)(wishlist|wish)"

在这个例子中,我们是在匹配“air”或者“ipadair”,但仅仅“air”就能匹配到这两者。对于“wish”也是一样。因为我们没有使用捕获组,所以输出可以简化为:

"air.*wish"

其他的模式也是如此,这就引出了一个问题:这个正则表达式到底在做什么呢?

看起来你只是想检查一些特定的单词模式在你的文章中是否按某种顺序出现。如果是这样的话,我们可以在Python中更快地实现这个,而不需要用正则表达式:

def has_phrases(in_string, phrases):
    for words in phrases:
        start = 0
        match = True

        # Match all words
        for word in words:
            # Each word must come after the ones before
            start = in_string.find(word, start)
            if start == -1:
                match = False
                break

        if match:
            return True

phrases = [
    ['upgrade'],
    ['air', 'wish'],
    ['intrigued', 'air'],
    ['replac', 'with', 'air' ],
]

print has_phrases("... air ... wish ...", phrases)      # True!
print has_phrases("... horse ... magic ...", phrases)   # None

当然,如果你只是给了一个简化的例子,并且打算使用非常复杂的正则表达式,那这个方法就不够用了。

希望这能帮到你!

撰写回答