Java RegEx to validate Gmail address
I’ve written about Java regular expression to validate email addresses before. Today I am sharing another Java regex to validate Gmail address.
It is quite simple and self-explanatory.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmailRegEx { public static void main(String args[]) { try (Scanner in = new Scanner(System.in)) { System.out.print("Enter Gmail address:"); String emailAddress = in.nextLine(); if (isGmailAddress(emailAddress)) { System.out.println(emailAddress + " is a valid Gmail address."); } else { System.out.println(emailAddress + " is not a valid Gmail address."); } } catch (Exception e) { e.printStackTrace(); } } public static boolean isGmailAddress(String emailAddress) { String expression = "^[\\w.+\\-]+@gmail\\.com$"; CharSequence inputStr = emailAddress; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); return matcher.matches(); } }
First, we have to build the regex to check for Gmail address.
String expression = "^[\\w.+\\-]+@gmail\\.com$";
Then we just have to compare input email address with this expression. If it is a valid Gmail address the method will return true, otherwise it will return false.