다음 정규식은 빈 입력을 포함하여 주어진 이메일 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