正则表达式检测多个字符串之一 [英] Regex to detect one of several strings

查看:54
本文介绍了正则表达式检测多个字符串之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份属于多个域的电子邮件地址列表.我想要一个正则表达式来匹配属于三个特定域的地址(例如: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)

所以这些将匹配:

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

这不会:

  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.

推荐答案

使用竖线符号表示或":

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆