I am not entirely sure what you would deem as a valid email, but I did the following based on this assumption:
A valid email is a string that has at least 1 word character,
followed by the '@' sign, followed by at least 1
alphabet, followed by the '.' character, and ending with
at least 1 alphabet
Here's the code using regex:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuickTester {
private static String[] emails = {"[email protected]",
"randomStringThatMakesNoSense",
"abc@@@@@", "thisIsRegex@rubbish",
"test123.com", "[email protected]",
"@[email protected]"};
public static void main(String[] args) {
for(String email : emails) {
System.out.printf("%s is %s.%n",
email,
(isValidEmail(email) ? "Valid" : "Not Valid"));
}
}
// Assumes that domain name does not contain digits
private static boolean isValidEmail (String emailStr) {
// Looking for a string that has at least 1 word character,
// followed by the '@' sign, followed by at least 1
// alphabet, followed by the '.' character, and ending with
// at least 1 alphabet
String emailPattern =
"^\\w{1,}@[a-zA-Z]{1,}\\.[a-zA-Z]{1,}$";
Matcher m = Pattern.compile(emailPattern).matcher(emailStr);
return m.matches();
}
}
Output:
[email protected] is Valid.
randomStringThatMakesNoSense is Not Valid.
abc@@@@@ is Not Valid.
thisIsRegex@rubbish is Not Valid.
test123.com is Not Valid.
[email protected] is Valid.
@[email protected] is Not Valid.
Based on your definition of a valid email, you could adjust the Pattern accordingly. I hope this helps!
@token but uses special format specifiers such a%sfor a string or%dfor a number. See docs.oracle.com/javase/7/docs/api/java/util/… . It does not matter where these values appear in the String. They will be inserted in the place of the corresponding specifier.