Extracts user name from email. - Java java.util.regex

Java examples for java.util.regex:Match Email

Description

Extracts user name from email.

Demo Code



public class Main{
    public static void main(String[] argv){
        String email = "123@rjava2s.com";
        System.out.println(extractUserNameFromEmail(email));
    }//from ww  w.  j  av a 2 s. co  m
    /**
     * Extracts user name from email.
     *
     * @param email The email to extract the user name.
     * @return user name part of address, null if not an e-mail address.
     * 
     */
    public static String extractUserNameFromEmail(String email) {

        String user = null;

        try {
            user = email.substring(0, email.indexOf('@'));
        } catch (Exception e) {
            // Suppressing on purpose. Any exception in substring or indexOf
            // means the user part of the string is null.
        }

        return user;
    }
}

Related Tutorials