Java 正则表达式程序来验证电子邮件,包括空字段也为有效字段
以下正则表达式匹配给定的电子邮件 ID,包括 空输入 −
^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$其中:
^ 匹配句子的开头。
[a-zA-Z0-9._%+-] 匹配 @ 符号之前的英文(大小写)、数字、"+”、“_”、“.”和“-”其中一个字符。
+ 表示上述字符集重复一次或多次。
@ 匹配它本身。
[a-zA-Z0-9.-] 匹配 @ 符号之后英文(大小写)、数字、"." 和 "-”中的一个字符。
\.[a-zA-Z]{2,6} 在 “.” 之后为电子邮件域名的 2-6 个字符。
$ 表示句子的结束。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleTest {
public static void main( String args[] ) {
String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your e-mail: ");
String e_mail = sc.nextLine();
System.out.println("Enter your age: ");
int age = sc.nextInt();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(e_mail);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("e-mail value accepted");
} else {
System.out.println("e-mail not value accepted");
}
}
}输出 1
Enter your name: krishna Enter your e-mail: Enter your age: 20 e-mail value accepted
输出 2
Enter your name: Rajeev Enter your e-mail: rajeev.123@gmail.com Enter your age: 25 e-mail value accepted
示例 2
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter email address: ");
Scanner sc = new Scanner(System.in);
String e_mail = sc.nextLine();
//Regular expression
String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$";
boolean result = e_mail.matches(regex);
if(result) {
System.out.println("Valid match");
} else {
System.out.println("Invalid match");
}
}
}输出 1
Enter email address: rajeev.123@gmail.com Valid match
输出 2
Enter email address: Valid match
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP