Search code examples
regexregex-negationregex-lookaroundsregex-groupregex-greedy

Return only one group with OR condition in Regex


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 <[email protected]> - Return [email protected] as Group1.
Hello my Email Address is [mailto: [email protected]] - Return [email protected] as Group2.

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

Is there any way to do this?


Solution

  • 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.