Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple regex pattern for email [duplicate]

I've been trying to work this out for almost an hour now, and I can't see myself getting much further with it without any help or explanation. I've used regex before, but only ones that are very simple or had already been made.

This time, I'm trying to work out how to write a regex that achieves the following:

Email address must contain one @ character and at least one dot (.) at least one position after the @ character.

So far, this is all I've been able to work out, and it still matches email addresses that, for example, have more than one @ symbol.

.*?@?[^@]*\.+.*

It would be helpful if you can show me how to construct a regular expression that checks for a single @ and at least one full stop one or more spaces after the @. If you could break down the regex and explain what each bit does, that would be really helpful.

I want to keep it simple for now, so it doesn't have to be a full-on super-accurate email validation expression.

like image 808
Dog Lover Avatar asked May 07 '26 14:05

Dog Lover


1 Answers

With the help of ClasG's comment, I now have a fairly straightforward and suitable regex for my problem. For the sake of anyone learning regex who might come across this question in the future, I'll break the expression down below.

Expression: ^[^@]+@[^@]+\.[^@]+$

  • ^ Matches the beginning of the string (or line if multiline)
  • [^@] Match any character that is not in this set (i.e. not "@")
  • + Match one or more of this
  • @ Match "@" character
  • [^@] Match any character that is not in this set
  • + Match one or more
  • \. Match "." (full stop) character (backslash escapes the full stop)
  • [^@] Match any character that is not in this set
  • + Match one or more
  • $ Matches the end of the string (or line if multiline)

And in plain language:

  • Start at beginning of string or line
  • Include all characters except @ until the @ sign
  • Include the @ sign
  • Include all characters except @ after the @ sign until the full stop
  • Include all characters except @ after the full stop
  • Stop at the end of the string or line
like image 134
Dog Lover Avatar answered May 09 '26 04:05

Dog Lover