Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    /**
     * Validates an email based on regex -
     * "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" +
     * "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
     * 
     * @param email
     *            String containing email address
     * @return True if the email is valid; false otherwise.
     */
    public static boolean isEmailValid(String email) {
        boolean isValid = false;
        try {
            // Initialize reg ex for email.
            String expression = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
            CharSequence inputStr = email;
            // Make the comparison case-insensitive.
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputStr);
            if (matcher.matches()) {
                isValid = true;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        return isValid;
    }
}