Return 只有一组在正则表达式中具有 OR 条件

Return only one group with OR condition in Regex

我必须编写正则表达式来从句子中获取电子邮件地址。我希望它只与第 1 组一起返回。

正则表达式:

\[mailto:(.+)\]|<(.+@.+\..+)>

输入字符串:

Hello my Email Address is <foo@hotmail.com> - Return foo@hotmail.com as Group1.
Hello my Email Address is [mailto: foo@hotmail.com] - Return foo@hotmail.com as Group2.

我想如果有任何字符串匹配,那么它应该在 Group1 中返回。

有什么办法吗?

您可以使用正则表达式:

(?=\S+@)([^<\s]+@.*(?=[>\]]))
  • (?=\S+@) 正面前瞻,断言后面是任何非空白字符后跟 @.
  • ([^<\s]+@.*(?=[>\]])) 捕获组。捕获任何非空白、非 ^ 字符后跟 @,以及任何不超过 ]> 字符。

您可以测试正则表达式here