Regex to detect one of several strings

前端 未结 7 1686
野趣味
野趣味 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:28

    If the previous (and logical) answers about '|' don't suit you, have a look at

    http://metacpan.org/pod/Regex::PreSuf

    module description : create regular expressions from word lists

    0 讨论(0)
  • 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]
    0 讨论(0)
  • 2020-12-08 13:33

    Use the pipe symbol to indicate "or":

    /a@(foo|bar|baz)\b/
    

    If you don't want the capture-group, use the non-capturing grouping symbol:

    /a@(?:foo|bar|baz)\b/
    

    (Of course I'm assuming "a" is OK for the front of the email address! You should replace that with a suitable regex.)

    0 讨论(0)
  • 2020-12-08 13:33

    should be more generic, the a shouldn't count, although the @ should.

    /@(foo|bar|baz)(?:\W|$)/
    

    Here is a good reference on regex.

    edit: change ending to allow end of pattern or word break. now assuming foo/bar/baz are full domain names.

    0 讨论(0)
  • Ok I know you asked for a regex answer. But have you considered just splitting the string with the '@' char taking the second array value (the domain) and doing a simple match test

    if (splitString[1] == "foo" && splitString[1] == "bar" && splitString[1] == "baz")
    {
       //Do Something!
    }
    

    Seems to me that RegEx is overkill. Of course my assumption is that your case is really as simple as you have listed.

    0 讨论(0)
  • 2020-12-08 13:38
    ^(a|b)@(foo|bar|baz)$
    

    if you have this strongly defined a list. The start and end character will only search for those three strings.

    0 讨论(0)
提交回复
热议问题