Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Validate email cho phép rỗng - Java Regular Expressions


Regex cho phép blank

^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6})?$

Giải thích

  • ^...$ - toàn bộ chuỗi
  • (...)+? - group bắt buộc (nếu có)
  • ? cuối - toàn bộ group optional (0 hoặc 1 lần) → cho phép chuỗi rỗng

Ví dụ 1: Pattern/Matcher

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})?$";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập tên: "); sc.nextLine();
        System.out.println("Nhập email: "); String email = sc.nextLine();
        System.out.println("Nhập tuổi: "); sc.nextInt();
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        if (matcher.find()) {
            System.out.println("e-mail value accepted");
        } else {
            System.out.println("e-mail not value accepted");
        }
    }
}

Kết quả

Nhập tên: krishna
Nhập email: 
Nhập tuổi: 20
e-mail value accepted
Nhập tên: Rajeev
Nhập email: rajeev.123@gmail.com
Nhập tuổi: 25
e-mail value accepted

Ví dụ 2: String.matches()

String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6})?$";
System.out.println("".matches(regex));        // true
System.out.println("a@b.co".matches(regex));  // true
System.out.println("invalid".matches(regex)); // false

So sánh

RegexCho phép rỗng?
^...$Không
^(...)+?$Có (group optional)