简体   繁体   中英

Regex pattern to extract name from emails

I need some help to find a regex expression to extract user names from these emails: (Regex newbie here)

  • john.stewartcompany1@example.com
  • bruce.williamscompany1@example.com
  • richard.weiss@example.com
  • julia.palermocompany2@example.com
  • edward.philipscompany3@example.com

As you can see from the emails, almost all of them have the company name following the name. (company1, company2, company3)

But some emails have no company inserted. (See richard.weiss ) All of them will have @example.com

So I need to extract only the names, without the company, like this:

  • john.stewart
  • bruce.williams
  • richard.weiss
  • julia.palermo
  • edward.philips

I've come up with this pattern so far:

/(.+)(?=@example.com)/g

This only solves half of the problem, as it keeps the company name in the names.

  • john.stewart company1
  • bruce.williams company1
  • richard.weiss
  • julia.palermo company2
  • edward.philips company3

I still need to remove the company names from the user names. Is there a way to accomplish this with a single regex pattern ?

Any help appreciated.

PS: Thanks for the replies. I forgot to mention...

The company names are limited . We can safely assume from my example that there will be only company1 , company2 and company3 .

Thanks.

You can use

^.*?(?=(?:company1|company2|company3)?@)

See the regex demo .

Details :

  • ^ - start of string
  • .*? - any zero or more chars other than line break chars as few as possible
  • (?=(?:company1|company2|company3)?@) - a positive lookahead that requires the following subpatterns to match immediately to the right of the current location:
    • (?:company1|company2|company3)? - an optional company1 , company2 or company3 char sequence
    • @ - a @ char.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM