Java正则表达式电子邮件 [英] Java regex email

查看:108
本文介绍了Java正则表达式电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道使用正则表达式的电子邮件是不推荐的,但我必须测试这个。



我有这个正则表达式:

  \b [A-Z0-9 ._% - ] + @ [A-Z0-9 .-] + \。[AZ] {2,4} \b 

在Java中,我这样做:

  Pattern p = Pattern.compile(\\b [A-Z0-9 ._% - ] + @ [A-Z0-9 .-] + \\ [AZ] {2,4} \\b); 
Matcher m = p.matcher(foobar@gmail.com);

if(m.find())
System.out.println(Correct!);

然而,正则表达式失败,无论电子邮件是否受欢迎。任何想法?



谢谢,

解决方案

FWIW,这里是我们用来验证电子邮件地址的Java代码。 Regexp非常相似:

  public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
Pattern.compile(^ [A-Z0 -9 ._%+ - ] + @ [A-Z0-9 .-] + \\。[AZ] {2,6} $,Pattern.CASE_INSENSITIVE);

public static boolean validate(String emailStr){
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr);
return matcher.find();
}

工作相当可靠。


First of all, I know that using regex for email is not recommended but I gotta test this out.

I have this regex:

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

In Java, I did this:

Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
Matcher m = p.matcher("foobar@gmail.com");

if (m.find())
    System.out.println("Correct!");

However, the regex fails regardless of whether the email is wel-formed or not. A "find and replace" inside Eclipse works fine with the same regex.

Any idea?

Thanks,

解决方案

FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:

public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
    Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

public static boolean validate(String emailStr) {
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr);
        return matcher.find();
}

Works fairly reliably.

这篇关于Java正则表达式电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆