Biểu thức chính quy sau khớp với id e-mail nhất định bao gồm cả đầu vào trống -
^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})?$ Ở đâu,
-
^ khớp với đầu câu.
-
[a-zA-Z0-9 ._% + -] khớp với một ký tự trong bảng chữ cái tiếng Anh (cả hai trường hợp), các chữ số, "+", "_", ".", "" và "-" trước ký hiệu @ .
-
+ cho biết sự lặp lại của bộ ký tự đã đề cập ở trên một hoặc nhiều lần.
-
@ khớp với chính nó
-
[a-zA-Z0-9.-] khớp với một ký tự trong bảng chữ cái tiếng Anh (cả hai trường hợp), chữ số, "." và "-" sau ký hiệu @
-
\. [a-zA-Z] {2,6} hai đến 6 chữ cái cho miền email sau "."
-
$ chỉ ra cuối câu
Ví dụ 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");
}
}
} Đầu ra1
Enter your name: krishna Enter your e-mail: Enter your age: 20 e-mail value accepted
Đầu ra 2
Enter your name: Rajeev Enter your e-mail: rajeev.123@gmail.com Enter your age: 25 e-mail value accepted
Ví dụ 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");
}
}
} Đầu ra 1
Enter email address: rajeev.123@gmail.com Valid match
Đầu ra 2
Enter email address: Valid match