Regex conditional non-capturing group

54 Views Asked by At

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.

[email protected] => test
[email protected] => [email protected]

here is my regex

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

I looked at this post but no luck.

2

There are 2 best solutions below

5
Barmar On BEST ANSWER
^(.+?)(?:(?:@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

0
Cary Swoveland On

You can match the regular expression

(.+(?=@example1\.com$)|.*)

for the specified domain "example1.com".

Demo

If, instead of saving the result to capture group 1, it can simply be what is matched by the regular expression, which often is regarded as capture group 0, you could use the regular expression

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

The regular expression can be broken down as follows.

(                   # begin capture group 1
  .+                # match one or more characters other than
                    # line terminators, as many as possible
  (?=               # begin a positive lookahead
    @example1\.com  # match "@example1.com"
    $               # match end of string
  )                 # end the positive lookahead
  |                 # or
  .*                # match zero or more characters other than 
                    # line terminators, as many as possible
)                   # end capture group 1