使用正則表示式檢查電子郵件地址是否有效


若要驗證給定的輸入字串是否有效的電子郵件 ID,請將其與以下 正則表示式進行匹配,以匹配電子郵件 ID −

"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"

其中,

  • ^匹配句子的開頭。

  • [a-zA-Z0-9+_.-] 匹配 “@” 符號前英文字母表(大小寫)、數字,“+”、“_”、“.” 和 “-” 中的一個字元。

  • + 表示上述字元集重複出現一次或多次。

  • @ 匹配本身。

  • [a-zA-Z0-9.-] 匹配 “@” 符號後英文字母表(大小寫)、數字,“.” 和 “–” 中的一個字元。

  • $ 表示句子的結尾。

示例

import java.util.Scanner;
public class ValidatingEmail {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your Email: ");
      String phone = sc.next();
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Matching the given phone number with regular expression
      boolean result = phone.matches(regex);
      if(result) {
         System.out.println("Given email-id is valid");
      } else {
         System.out.println("Given email-id is not valid");
      }
   }
}

Output 1

Enter your Email:
example.samplemail@gmail.com
Given email-id is valid

Output 2

Enter your Email:
sample?examplemail@gmail.com
Given email-id is not valid

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your email id: ");
      String phone = sc.next();
      //Regular expression to accept valid email id
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(phone);
      //Verifying whether given phone number is valid
      if(matcher.matches()) {
         System.out.println("Given email id is valid");
      } else {
         System.out.println("Given email id is not valid");
      }
   }
}

Output 1

Enter your name:
vagdevi
Enter your email id:
sample.123@gmail.com
Given email id is valid

Output 2

Enter your name:
raja
Enter your email id:
raja$test@gmail.com
Given email id is not valid

從頭開始學習 Java,請使用我們的Java 教程

更新時間:19-Feb-2024

7.6 萬+ 瀏覽量

助力您的 職業

完成課程獲取認證

開始學習
廣告