Java 如何判断随机字符串是电子邮件地址还是其他内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18463848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:51:07  来源:igfitidea点击:

How to tell if a random string is an email address or something else

javaemail

提问by Stephen Connolly

I don't think that this question has been asked before... I certainly cannot find something with this requirement.

我不认为以前有人问过这个问题......我当然找不到符合这个要求的东西。

Background

背景

There is an API that returns ID's of people. In general the ID should be treated as being case sensitive... but if the ID is actually their email address... and you are talking to a less than stellar implementation of this API that returns a mixed case version of their email address, there is plenty of fun to be had...

有一个 API 可以返回人的 ID。一般来说,ID 应该被视为区分大小写......但如果 ID 实际上是他们的电子邮件地址......并且你正在谈论这个 API 的一个不太出色的实现,它返回他们的电子邮件地址的混合大小写版本,有很多乐趣可以享受......

So you are talking to one implementation... it gives you back URL like things as the ID, e.g.

所以你正在谈论一个实现......它为你提供了像ID一样的URL,例如

  • http://foo.bar.com/blahblahblah
  • http://foo.bar.com/blahblahblah

You could next be talking to another implementation... that gives you back some non-obvious ID, e.g.

您接下来可能会与另一个实现交谈......它会给您一些不明显的 ID,例如

  • asjlhdésdj678hjghas7t7qhjdhg£
  • asjlhdésdj678hjghas7t7qhjdhg£

You could be talking to a nice implementation which gives you back a nice lowercase email address:

你可能正在谈论一个很好的实现,它会给你一个很好的小写电子邮件地址:

Or you could be talking to the less than stellar implementation that returns the exactly equivalent ID

或者您可能正在谈论返回完全等效 ID 的不太出色的实现

RFC 2821 states that only the mailbox is case sensitive, but that exploiting the case sensitivity will cause a raft of inter-op issues...

RFC 2821 指出只有邮箱区分大小写,但利用区分大小写会导致大量互操作问题......

What I want to do is identify the strings that are emails and force the domain to lowercase. Identifying the URI like strings is easier as the scheme is either httpor httpsand I just need to lowercase the domain name which is a lot easier to parse.

我想要做的是识别作为电子邮件的字符串并强制域为小写。识别URI字符串一样是容易的方案是要么http还是https我只需要小写域名这是一个容易得多解析。

Question

If given a string provided by an external service, is there a test I can use that will determine if the string is an email address so I can force the domain name to lower case?

如果给定外部服务提供的字符串,是否有我可以使用的测试来确定该字符串是否是电子邮件地址,以便我可以强制域名为小写?

It is acceptable for a small % of email addresses to be missed and not get the domain name lowercased. (False negatives allowed)

遗漏一小部分电子邮件地址并且不使域名小写是可以接受的。(允许假阴性)

It is not acceptable to force part of a string to lowercase if it is not the domain part of an email address. (False positives not allowed)

如果字符串的一部分不是电子邮件地址的域部分,则将其强制为小写是不可接受的。(不允许误报)

?Update

?更新

Note that this question is subtly different from thisand thisas in the context of those two questions you already know that the string is supposed to be an email address.

请注意,此问题与thisthis略有不同,因为在这两个问题的上下文中,您已经知道该字符串应该是电子邮件地址

In the context of this question we do not know if the string is an email address or something else... which makes this question different

在这个问题的上下文中,我们不知道字符串是电子邮件地址还是其他东西......这使得这个问题有所不同

采纳答案by Stephen Connolly

Thanks to @Dukeling

感谢@Dukeling

private static toLowerCaseIfEmail(String string) {
    try {
        new InternetAddress(string, true);
    } catch (AddressException e) {
        return string;
    }
    if (string.trim().endsWith("]")) {
        return string;
    }
    int lastAt = string.lastIndexOf('@');
    if (lastAt == -1) {
        return string;
    }
    return string.substring(0,lastAt)+string.substring(lastAt).toLowerCase();
}

should, from what I can tell, do the required thing.

应该,据我所知,做所需的事情。

Update

更新

Since the previous one ignored the possibility of (comment)syntax after the last @... which lets face it, if we see them should just bail out fast and return the string unmodified

由于前一个忽略了(comment)最后一个之后语法的可能性@......让我们面对它,如果我们看到它们应该快速退出并返回未修改的字符串

private static toLowerCaseIfEmail(String string) {
    try {
        new InternetAddress(string, true);
    } catch (AddressException e) {
        return string;
    }
    int lastAt = string.lastIndexOf('@');
    if (lastAt == -1 
        || string.lastIndexOf(']') > lastAt
        || string.lastIndexOf(')' > lastAt) {
        return string;
    }
    return string.substring(0,lastAt)+string.substring(lastAt).toLowerCase();
}

回答by Shiv

You can use following for verifying an email;

您可以使用以下内容来验证电子邮件;

String email ="[email protected]"
Pattern p = Pattern.compile(".+@.+\.[a-z]+");
Matcher m = p.matcher(email);
boolean matchFound = m.matches();
if (matchFound) {
    //your work here
}

回答by Kumar Vivek Mitra

-Try the below code, this may be helpful to you.

-试试下面的代码,这可能对你有帮助。

public class EmailCheck {

    public static void main(String[] args){


        String email = "[email protected]";
        Pattern pattern = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}");
        Matcher mat = pattern.matcher(email);

        if(mat.matches()){

            System.out.println("Valid email address");
        }else{

            System.out.println("Not a valid email address");
        }
    }

}

-Also take a look at this site, which shows another deeper validation using regular expression. Deeper validation using regular expression

-也看看这个站点,它显示了另一个使用regular expression. 使用正则表达式进行更深入的验证

回答by Juriy Brezmen

        Pattern pattern = Pattern.compile("^[A-Za-z0-9._]{1,16}+@{1}+[a-z]{1,7}\.[a-z]{1,3}$");
        Matcher mail = pattern.matcher(your_mail);

        if (mail.find()) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }