Email Validation

CHALLENGE DESCRIPTION:

You are given several strings that may/may not be valid emails. You should write a regular expression that determines if the email id is a valid email id or not. You may assume all characters are from the english language.

INPUT SAMPLE:

Your program should accept as its first argument a filename. This file will contain several text strings, one per line. Ignore all empty lines. E.g.

foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com

OUTPUT SAMPLE:

Print out ‘true’ (all lowercase) if the string is a valid email. Else print out ‘false’ (all lowercase). E.g.

true
false
false
true

Solution:

import java.io.File;
import java.io.FileNotFoundException;

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

public class Main {

    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.startFileRead(args[0]);
    }

    public void startFileRead(String filePath) throws FileNotFoundException {
        File file = new File(filePath);


        if (file.exists()) {
            Scanner s = new Scanner(file);
            int n = 0;

            boolean tmp = false;
            while ((s.hasNextLine())) {
                tmp = EmailValidation(s.nextLine());
                System.out.println(tmp);
            }

        }
    }

    public boolean EmailValidation(String line) {
        Pattern pattern;
        Matcher matcher;
        String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(line);
        return matcher.matches();
    }
}

Leave a Reply