How to filter a string in java with a specific range (email format)

I have a line in Java called Kiran<kiran@gmail.com>. I want to get String only kiran@gmail.com by deleting other content.

String s1= kiran<kiran@gmail.com>

The exit should be kiran@gmail.com

Please help me in resolving this issue.

+5
source share
2 answers

If you are trying to parse email addresses, I would recommend using the InternetAddress class . This is part of Java EE (if you are using Java SE, you need to add the javax.mail dependency ).

This class is able to parse a string containing an email address such as yours.

String s1 = "kiran<kiran@gmail.com>";
InternetAddress address = new InternetAddress(s1);
String email = address.getAddress();

I think so:

  • Your algorithm automatically meets the standards.
  • , .
+4

.

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);
    }
+2

All Articles