Add Dash to 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 abc.xyz@example.com , but now some email addresses have dashes in them such as abc-def.xyz@example.com 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. eg 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]+$

The correct Regex fix is below.

OLD Regex Expression

^[a-zA-Z0-9_.]+@[a-zA-Z0-9_]+.[a-zA-Z0-9_]+$

NEW Regex Expression

^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$
链接地址: http://www.djcxy.com/p/92878.html

上一篇: jQuery验证插件允许电子邮件中的特殊字符?

下一篇: 将短划线添加到Java正则表达式