Java正则表达式校验某个字符串是否是合格的email
可以借助正则表达式校验某个字符串是否是合规的电子邮箱。对于邮箱的正则表达式有严格的模式,如:^[a-zA-Z0-9_ &*-] (?:\.[a-zA-Z0-9_ &*-] )*@(?:[a-zA-Z0-9-] \.) [a-zA-Z]{2,7}$
对应的Java实现如下:
package EmailValidationExamples.Regex01;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidatorStrict {
private static final String EMAIL_PATTERN =
"^[a-zA-Z0-9_ &*-] (?:\.[a-zA-Z0-9_ &*-] )*@(?:[a-zA-Z0-9-] \.) [a-zA-Z]{2,7}$";
//initialize the Pattern object
private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
// check if the email is valid
public static boolean isValid(final String email) {
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}
对应的测试代码如下:
代码语言:javascript复制package EmailValidationExamples.Regex01;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidation {
public static void main(String args[]) {
//adding emails to an array list
List<String> emails = new ArrayList<String>();
//valid email addresses
emails.add("alice@example.com");
emails.add("alice.bob@example.com");
emails.add("alice@example.me.org");
//invalid email addresses
emails.add("alice.example.com");
emails.add("alice..bob@example.com");
emails.add("alice@.example.me.org");
//searching for occurrences of regex
for (String email : emails) {
System.out.println("Email " email " is "
(EmailValidatorStrict.isValid(email) ? "valid" : "invalid"));
}
}
}
执行结果如下图所示: