how to do re.compile() with a list in python

前端 未结 5 577
日久生厌
日久生厌 2020-12-04 20:08

I have a list of strings in which I want to filter for strings that contains keywords.

I want to do something like:

fruit = re.compile(\'apple\', \'         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 20:43

    You can create one regular expression, which will match, when any of the terms is found:

    >>> s, t = "A kiwi, please.", "Strawberry anyone?"
    >>> import re
    >>> pattern = re.compile('apple|banana|peach|plum|pineapple|kiwi', re.IGNORECASE)
    >>> pattern.search(s)
    <_sre.SRE_Match object at 0x10046d4a8>
    >>> pattern.search(t) # won't find anything
    

提交回复
热议问题