Return only one group with OR condition in Regex

我怕爱的太早我们不能终老 提交于 2019-12-11 15:17:24

问题


I have to write a Regex to fetch Email Address from a sentence. I want it to be returned with Group 1 only.

Regex:

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

Input String:

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.

I want if any of the string matches then it should be returned in Group1.

Is there any way to do this?


回答1:


You may use regular expression:

(?=\S+@)([^<\s]+@.*(?=[>\]]))
  • (?=\S+@) Positive lookahead, assert that what follows is any non-whitespace characters followed by @.
  • ([^<\s]+@.*(?=[>\]])) Capture group. Capture any non-whitespace, non ^ character followed by @, and anything up to either a ] or > character.

You can test the regular expression here.



来源:https://stackoverflow.com/questions/51542531/return-only-one-group-with-or-condition-in-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!