简体   繁体   English

Java - 使用regex从requestURI中提取电子邮件地址

[英]Java - Extract email address from requestURI with regex

I'm trying to extract the email address from the requestURI with regex below is the email regex based on RFC-2822 and it works well with validations 我试图从requestURI中提取电子邮件地址,下面是正则表达式,是基于RFC-2822的电子邮件正则表达式,它可以很好地验证

private final transient String EMAIL_REGEX = 
            "^([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]"
            + "+|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22)"
            + "(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+"
            + "|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22))"
            + "*\\x40([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+"
            + "|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d)"
            + "(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]"
            + "+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d))*$";

I'm trying to reuse the same regex to match and extract the email address from the URI /something/users/myemail@email.com/somethingelse , with Matcher.group(0) I get the output /something/users/myemail@email.com where as my intended output is only the email address from the URI. 我正在尝试重用相同的正则表达式来匹配并从URI /something/users/myemail@email.com/somethingelse提取电子邮件地址,使用Matcher.group(0)我得到输出/something/users/myemail@email.com我的目标输出只是URI中的电子邮件地址。

I have come up with this regex update: 我已经提出了这个正则表达式更新:

private static String EMAIL_REGEX =
        "([^/\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]"
        + "+|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22)"
        + "(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+"
        + "|\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22))"
        + "*\\x40([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+"
        + "|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d)"
        + "(\\x2e([^/\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]"
        + "+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d))*";

Please pay attention at the [^/\\\\x00 at the beginning and on the second-to-last line. 请注意[^/\\\\x00开头和倒数第二行。

See the online demo 请参阅在线演示

String s = "/something/users/myemail@email.com/somethingelse";         
Matcher m = Pattern.compile(EMAIL_REGEX).matcher(s);
while (m.find())
{
    System.out.println(m.group());
} // => myemail@email.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM