From 5c714758f87ad68c6db0c2fe3540b4cdba54045c Mon Sep 17 00:00:00 2001 From: Armando Jesus Gomez Parra Date: Sat, 23 Oct 2021 19:46:28 -0500 Subject: [PATCH] Add Check Email --- Strings/CheckEmail.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Strings/CheckEmail.java diff --git a/Strings/CheckEmail.java b/Strings/CheckEmail.java new file mode 100644 index 000000000000..fb9824b2b4fe --- /dev/null +++ b/Strings/CheckEmail.java @@ -0,0 +1,34 @@ +package Strings; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Example of email address validation. Checks if a given string is a valid email or not. + */ +public class CheckEmail { + + public static void main(String[] args) { + assert isEmail("hello@gmail.com"); + assert isEmail("iamweasel@yahoo.com.mx"); + assert isEmail("coco@hotmail.com"); + assert !isEmail("coco@hotmail@google.com"); + assert !isEmail("www.google.com"); + assert !isEmail("hello world"); + assert !isEmail(null); + } + + /** + * Checks if the given string is an email address + * + * @param stringToEvaluate the string to evaluate + * @return {@code true} if stringToEvaluate is an email address, otherwise {@code false} + */ + public static boolean isEmail(String stringToEvaluate) { + if(Objects.isNull(stringToEvaluate)) return false; + String emailRegex = "^[A-Za-z0-9_+&*-]+(?:\\.[A-Za-z0-9_+&*-]+)*@(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,7}$"; + return Pattern.compile(emailRegex) + .matcher(stringToEvaluate) + .matches(); + } +}