Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Dash to Java Regex

Tags:

java

regex

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?

like image 562
mattdonders Avatar asked May 03 '16 17:05

mattdonders


2 Answers

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)) ....
like image 102
Federico Piazza Avatar answered Nov 12 '22 13:11

Federico Piazza


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]+$
like image 4
rock321987 Avatar answered Nov 12 '22 14:11

rock321987