Java Email Validate format(String emails)

Here you can find the source of format(String emails)

Description

Parses the parameter for valid email addresses

License

Open Source License

Parameter

Parameter Description
emails is one or more email adresses separated by space(\\s), or | or ; or ,

Return

String comma delimeted list of email addresses

Declaration

public static String format(String emails) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    /**//from   w  w w. ja va 2 s . c  o m
     * Parses the parameter for valid email addresses
     * @param emails is one or more email adresses separated by space(\\s), or | or ; or ,
     * @return String comma delimeted list of email addresses
     */
    public static String format(String emails) {
        if (emails == null)
            return "";
        StringBuilder target = new StringBuilder();
        // Create a pattern to match breaks
        Pattern p = Pattern.compile("[,\\s|;]+");
        // Split input with the pattern
        String[] result = p.split(emails);
        for (int i = 0; i < result.length; i++) {
            if (!isEmailValid(result[i]))
                continue;
            target.append(result[i]);
            if (i + 1 != result.length)
                target.append(",");
        }
        return target.toString();
    }

    public static boolean isEmailValid(String emailAddress) {
        try {
            //InternetAddress.parse(emailAddress);
            Pattern alpha = Pattern.compile("[a-zA-Z0-9]@([\\w-]+\\.)+[\\w-]{2,4}$");
            Matcher matcher = alpha.matcher(emailAddress.trim());
            if (matcher.find())
                return true;
        } catch (Exception ae) {
            return false;
        }
        return false;
    }

    /**
     * Helper method to convert array of strings to comma delimeted string
     * @param emails
     * @return comma delimeted string
     */
    public static String toString(String[] emails) {
        if (emails == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < emails.length; i++) {
            sb.append(emails[i]);
            if (i + 1 != emails.length)
                sb.append(",");
        }
        return sb.toString();
    }
}

Related

  1. checkEmailWithSuffix(String email)
  2. cleanUpEmailAddress(CharSequence address)
  3. containsEmail(String chunk)
  4. extractEmail(String string, StringBuffer sb)
  5. extractEmailAddresses(final String text)
  6. getEmail(String author)
  7. getEmailAddressFromDN(String dn)
  8. getEmailListStr(String tempStr)
  9. getEmails(String str)