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*<([\w\d@\.]*)>,(\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 Smith\n" + "<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("[\\n\\r]+", ""); String email = m.group(2).replaceAll("[\\n\\r]+", ""); 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?

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Extracting Names and Email address from String with regex