正则表达式检测多个字符串之一 [英] Regex to detect one of several strings
问题描述
我有一份属于多个域的电子邮件地址列表.我想要一个正则表达式来匹配属于三个特定域的地址(例如:foo、bar、& baz)
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)
所以这些将匹配:
- a@foo
- a@bar
- b@baz
这不会:
- a@fnord
理想情况下,这些都不匹配(尽管这对这个特定问题并不重要):
Ideally, these would not match either (though it's not critical for this particular problem):
- a@foobar
- b@foofoo
将问题抽象一点:我想匹配一个字符串,该字符串至少包含一个给定的子字符串列表.
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/
(当然,我假设电子邮件地址前面可以使用a
"!您应该将其替换为合适的正则表达式.)
(Of course I'm assuming "a
" is OK for the front of the email address! You should replace that with a suitable regex.)
这篇关于正则表达式检测多个字符串之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!