regexcapturing-group

Regex conditional non-capturing group


I am trying to extract the email`s username if the email is from a specific domain. otherwise, get the full email. I need the result to be set in Group 1.

test@example1.com => test
test@example2.com => test@example2.com

here is my regex

^(.*)?(?:@example1\.com)|(?=@example2\.com)$

I looked at this post but no luck.


Solution

  • ^(.+?)(?:(?:@example1\.com)?|(?=@))$
    

    This uses a non-greedy quantifier inside the capture group, so it will only match up to @example1.com if that domain is in the input. Otherwise it uses a lookahead to require that there be @domain in the input.

    We put a group around the alternatives so they don't split the whole regexp into separate alternatives. Your regexp only has the capture group in the first alternative.

    DEMO