Day 17 - Java

Problem Statement:

You are given a set of email addresses and phone numbers. You need to validate each email address and phone number according to the following rules:

Email addresses should follow the standard format: [username]@[domain].[extension], where [username] can contain alphanumeric characters, underscores, hyphens, and periods, [domain] can contain alphanumeric characters and hyphens, and [extension] must be a valid domain extension of length 2 to 7 characters.

Phone numbers should be in one of the following formats:

For the USA: +1 [3 digits]-[3 digits]-[4 digits]

For India: +91 [5 digits] [5 digits]

Your task is to implement a program to validate the given email addresses and phone numbers using the provided regex patterns.

Input Format:

The first line contains two integers, N and M, separated by a space, where N is the number of email addresses and M is the number of phone numbers.

This is followed by N lines, each containing an email address.

Then, there are M lines, each containing a phone number.

Output Format:

For each email address and phone number, print "Valid" if it satisfies the respective format, and "Invalid" otherwise, each on a new line.

Constraints:

1 <= N, M <= 100

The email addresses and phone numbers consist only of alphanumeric characters, hyphens, underscores, spaces, and periods.

The length of the username part of the email address is at most 64 characters.

The length of the domain part of the email address is at most 253 characters.

The length of the extension part of the email address is between 2 and 7 characters.

The phone numbers contain only digits and spaces.

For USA phone numbers, the first digit after the country code should not be 0 or 1.

Sample Input:

5 5

coding@gmail.com

coding@yahoo.com

coding.python@com

coding.scratch@com.co.in

coding@master.c

+1 123-456-7890

+91 12345 67890

+1 123-456-789

+91 1234 567890

+911234567890

Sample Output:

Valid

Valid

Invalid

Valid

Invalid

Valid

Valid

Invalid

Invalid

Invalid

Explanation:

The first two email addresses are valid according to the provided regex pattern.

The third email address contains an invalid character ('.') in the domain part.

The fourth email address is valid.

The fifth email address has an invalid domain extension.

The first and second phone numbers are valid USA and Indian phone numbers respectively.

The third phone number is invalid because it has an incomplete number of digits after the country code.

The fourth phone number is invalid because it uses a space instead of a hyphen for separation.

The fifth phone number is invalid because it has an extra digit after the country code.


SOLUTION:

import java.util.Scanner;

import java.util.regex.*;

public class EmailPhoneValidator {

    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";

    private static final String USA_PHONE_REGEX = "^\\+1 \\d{3}-\\d{3}-\\d{4}$";

    private static final String INDIA_PHONE_REGEX = "^\\+91 \\d{5} \\d{5}$";


    public static boolean isValidEmail(String email) {

        Pattern pattern = Pattern.compile(EMAIL_REGEX);

        Matcher matcher = pattern.matcher(email);

        return matcher.matches();

    }


    public static boolean isValidPhoneNumber(String phoneNumber) {

        if (phoneNumber.startsWith("+1")) {

            Pattern pattern = Pattern.compile(USA_PHONE_REGEX);

            Matcher matcher = pattern.matcher(phoneNumber);

            return matcher.matches();

        } else if (phoneNumber.startsWith("+91")) {

            Pattern pattern = Pattern.compile(INDIA_PHONE_REGEX);

            Matcher matcher = pattern.matcher(phoneNumber);

            return matcher.matches();

        } else {

            return false;

        }

    }


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        String[] counts = sc.nextLine().split(" ");

        int emailCount = Integer.parseInt(counts[0]);

        int phoneCount = Integer.parseInt(counts[1]);


        for (int i = 0; i < emailCount; i++) {

            String email = sc.nextLine();

            System.out.println(isValidEmail(email) ? "Valid" : "Invalid");

        }


        for (int i = 0; i < phoneCount; i++) {

            String phoneNumber = sc.nextLine();

            System.out.println(isValidPhoneNumber(phoneNumber) ? "Valid" : "Invalid");

        }

        sc.close();

    }

}


Email Regular Expression (EMAIL_REGEX):

This regex pattern is used to validate email addresses.

^[a-zA-Z0-9_+&*-]+: This part matches the username of the email. It allows alphanumeric characters, underscores, and certain special characters (+, &, *, -).

(?:\\.[a-zA-Z0-9_+&*-]+)*: This part matches the domain and extension of the email. It allows periods to separate domain parts and alphanumeric characters, underscores, and certain special characters in the domain and extension parts.

@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$: This part matches the domain extension of the email. It allows alphanumeric characters and hyphens in the domain and ensures that the extension is between 2 and 7 characters.

USA Phone Regular Expression (USA_PHONE_REGEX):

This regex pattern is used to validate phone numbers with the country code for the USA.

^\\+1: This part matches the country code, which is "+1".

\\d{3}-\\d{3}-\\d{4}$: This part matches the phone number format, which consists of three digits, a hyphen, another three digits, a hyphen, and finally four digits.

India Phone Regular Expression (INDIA_PHONE_REGEX):

This regex pattern is used to validate phone numbers with the country code for India.

^\\+91: This part matches the country code, which is "+91".

\\d{5} \\d{5}$: This part matches the phone number format, which consists of five digits, a space, another five digits.

Insights:

  • The code is structured into separate methods for validating email addresses (isValidEmail()) and phone numbers (isValidPhoneNumber()).
  • Regular expressions are utilized to define patterns for validating email addresses and phone numbers.
  • The program distinguishes between USA and India phone numbers based on their country codes ("+1" and "+91" respectively) and applies the corresponding regex pattern for validation.
  • The program handles errors gracefully by checking for unsupported country codes in phone numbers and returning false in such cases.
  • The program provides clear output messages ("Valid" or "Invalid") for each email address and phone number, making it easy for users to interpret the validation results.
Life's like a regex; understand its patterns, learn from experiences, and craft your unique path.

Happy Coding! :)

Comments