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

更新時間:10-01-2020

239 次瀏覽

啟動您的 職業

完成課程以獲得認證

開始
廣告