Regex to detect one of several strings

前端 未结 7 1695
野趣味
野趣味 2020-12-08 13:20

I\'ve got a list of email addresses belonging to several domains. I\'d like a regex that will match addresses belonging to three specific domains (for this example: foo, bar

7条回答
  •  再見小時候
    2020-12-08 13:31

    You don't need a regex to find whether a string contains at least one of a given list of substrings. In Python:

    def contain(string_, substrings):
        return any(s in string_ for s in substrings)
    

    The above is slow for a large string_ and many substrings. GNU fgrep can efficiently search for multiple patterns at the same time.

    Using regex

    import re
    
    def contain(string_, substrings):
        regex = '|'.join("(?:%s)" % re.escape(s) for s in substrings)
        return re.search(regex, string_) is not None
    

    Related

    • Multiple Skip Multiple Pattern Matching Algorithm (MSMPMA) [pdf]

提交回复
热议问题