RegEx pattern to search characters before the "@" in an email

Viewed 143

I want to be able to query the database for email addresses matching a regex. An example of what I am trying to avoid is this:
In my database, I have a user with emailAddress of amy.user@gmail.com
I also have 700 users with the domain name @amyconsulting.com

The current search I have now will return 701 results instead of 1 when I try to search for Amy like so: ^.*amy.*$
How can I make this search only the characters before the @ symbol in the email address? Thanks in advance...

2 Answers

Another option is to use a negated character class [^@]* matching 0+ occurrences of any char except @

If you don't want to match a newline as well, you could use [^@\r\n]* or [^\s\@] to not match whitespaces as well.

^[^@]*amy[^@]*@[^@]+$

Explanation

  • ^ Start of string
  • [^@]* Match 0+ occurrences of any char except @
  • amy
  • [^@]* Match 0+ occurrences of any char except @
  • @ Match the @
  • [^@]+ Match 1+ occurrences of any char except @
  • $ End of string

Regex demo

This doesn't likely cover all email cases, but given the examples you've posted, you can start from here to improve your regex:

.*(amy).*@[\w]+(\.)[\w]+

It accepts strings that contain the word amy before an email regex pattern. Again, I didn't look up the best regex for email, but this one gives the idea of how you should approach your problem.

I recommend using Regex101, there's a very cool playground in there which helps to learn new regex symbols to figure out your problem.

Related