Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to detect one of several strings

Tags:

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.

like image 806
Craig Walker Avatar asked Mar 10 '09 20:03

Craig Walker


People also ask

How do you search for multiple words in a regular expression?

However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.

What is a capturing group regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


1 Answers

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

like image 79
Jason Cohen Avatar answered Sep 20 '22 13:09

Jason Cohen