Regex to detect one of several strings

regex

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, & baz)

So these would match:

  1. a@foo
  2. a@bar
  3. b@baz

This would not:

  1. a@fnord

Ideally, these would not match either (though it's not critical for this particular problem):

  1. a@foobar
  2. b@foofoo

Abstracting the problem a bit: I want to match a string that contains at least one of a given list of substrings.

Best Solution

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.)