Skip to content
Advertisement

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?

Advertisement

Answer

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,}$
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement