akila arasan
akila arasan

Reputation: 747

How to check if only one '@' symbol in email address using regex in java?

I am trying to create a regex in java to validate the email address. It should contain one uppercase one lowercase one digit only one @ symbol followed by '.'.So far i could only create this,

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*@)(?=.*\.).+$

scenarios like these

abC.8@gmailcom this address should return false

abC8@@gmail.com this also should return false

But the above regex returns true for all these scenarios.Could anyone help me correct this regex?

Upvotes: 1

Views: 5010

Answers (4)

Ivan_OFF
Ivan_OFF

Reputation: 347

I tried taking in consideration how my email should be and step by step i reached this conclusion, it will always accept '@' only in a specific part of the mail otherwise it won't be considered valid

^[^@,:; \t\r\n]+@[^@,:; \t\r\n]+\.[^@,:; \t\r\n]+$

Upvotes: 0

LukStorms
LukStorms

Reputation: 29647

You could add a negative lookahead to the regex to avoid 2 @

(?!.*@.*@)

But you could also make the last part of the regex more explicit, so that a double @ wouldn't match

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[\w.]+@[\w.]*\.[a-zA-Z0-9]+$

Or to allow more than just the [a-zA-Z0-9_] word characters and dots, but still excluding the whitespaces:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[^\s@]+@[^\s@]*\.[^\s@.]{2,}$

Upvotes: 4

Abhishek Gurjar
Abhishek Gurjar

Reputation: 7476

Try with below, It is not strict though but ignore your patterns which you've mentioned in question,

(?:[a-zA-Z\.\d]{1})+@\.com

Regex Demo

Upvotes: 1

Tamas Rev
Tamas Rev

Reputation: 7166

Validating emails with regexes is something that others have done before. According to emailregex.com, this is the java regex for emails:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

They claim that it works 99.99% of the time.

The other page, regular-expressions.info provides lots of other regex, starting with this simple one:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$

I.e. some valid characters, then the @, then the domain name. The step by step they show you how to build a regex that matches the RFC 5322.

Regarding making sure there's only one @, you can go with this:

^[^@]*@[^@]*$

Upvotes: 1

Related Questions