Extracting Names and Email address from String with regex

I have been trying to extract the names and email addresses from the following String that consists of multiple lines through regex in Java:

From: Kane Smith <Kane@smith.com>
To: John Smith <john@smith.com>, Janes Smith
    <jane@smith.org>, Tom Barter <tom@test.co.uk>, Other
    Weird @#$@<>#^Names <other@names.me>, 
    Long Long Long Long Name <longlong@name.com>
Date: Tue, 25 Oct 2011 15:45:59 +0000

I tried this regex: To:s?(([.*]+)s*<([wd@.]*)>,(s|n)*)+ But it doesn't work.

My intention is to extract each of the names and email addresses and put each name its email address together into groups. What I have done however, seems to work only when there is one single name and address. What should my regex be to do this?


    String s = "To: John Smith <john@smith.com>, Janes Smithn"
            + "<jane@smith.org>, Tom Barter <tom@test.co.uk>, Other n"
            + "Weird @#$@<>#^Names <other@names.me>, n"
            + "Long Long Long Long Name <longlong@name.com>";
    s = s.substring(3); // filter TO:
    System.out.println(s);
    // Use DOTALL pattern  
    Pattern p = Pattern.compile("(.*?)<([^>]+)>s*,?",Pattern.DOTALL);

    Matcher m = p.matcher(s);

    while(m.find()) {
        // filter newline
        String name = m.group(1).replaceAll("[nr]+", ""); 
        String email = m.group(2).replaceAll("[nr]+", "");
        System.out.println(name + " -> " + email);
    }

you can split each line on "," and then use javax.mail.internet.InternetAddress. That will take care of extracting the name and address.

Btw, where are you getting the headers from and why can't they be key values as they should be?

链接地址: http://www.djcxy.com/p/92804.html

上一篇: 弃用:函数eregi()已弃用

下一篇: 使用正则表达式从字符串中提取姓名和电子邮件地址