Regex to detect one of several strings
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:
This would not:
Ideally, these would not match either (though it's not critical for this particular problem):
Abstracting the problem a bit: I want to match a string that contains at least one of a given list of substrings.
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.)
^(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.
Use:
/@(foo|bar|baz).?$/i
Note the differences from other answers:
.?
- matching 0 or 1 dots, in case the domains in the e-mail address are "fully qualified" $
- to indicate that the string must end with this sequence, /i
- to make the test case insensitive. Note, this assumes that each e-mail address is on a line on its own.
If the string being matched could be anywhere in the string, then drop the $
, and replace it with s+
(which matches one or more white space characters)
上一篇: 如何在JavaScript Regexp中捕获任意数量的组?
下一篇: 正则表达式来检测几个字符串中的一个