I am trying to modify an existing Regex expression being pulled in from a properties file from a Java program that someone else built.
The current Regex expression used to match an email address is -
RR.emailRegex=^[a-zA-Z0-9_\\.]+@[a-zA-Z0-9_]+\\.[a-zA-Z0-9_]+$
That matches email addresses such as [email protected], but now some email addresses have dashes in them such as [email protected] and those are failing the Regex pattern match.
What would my new Regex expression be to add the dash to that regular expression match or is there a better way to represent that?
Basing on the regex you are using, you can add the dash into your character class:
RR.emailRegex=^[a-zA-Z0-9_\\.]+@[a-zA-Z0-9_]+\\.[a-zA-Z0-9_]+$
add
RR.emailRegex=^[a-zA-Z0-9_\\.-]+@[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_-]+$
Btw, you can shorten your regex like this:
RR.emailRegex=^[\\w.-]+@[\\w-]+\\.[\\w-]+$
Anyway, I would use Apache EmailValidator instead like this:
if (EmailValidator.getInstance().isValid(email)) ....
Meaning of -
inside a character class is different than used elsewhere. Inside character class -
denotes range. e.g. 0-9
. If you want to include -
, write it in beginning or ending of character class like [-0-9]
or [0-9-]
.
You also don't need to escape .
inside character class because it is treated as .
literally inside character class.
Your regex can be simplified further. \w
denotes [A-Za-z0-9_]
. So you can use
^[-\w.]+@[\w]+\.[\w]+$
In Java, this can be written as
^[-\\w.]+@[\\w]+\\.[\\w]+$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With