forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckEmail.java
More file actions
34 lines (30 loc) · 1.04 KB
/
CheckEmail.java
File metadata and controls
34 lines (30 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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();
}
}