Java 正则表达式程序用于验证包含空白字段的电子邮件是否有效

javaobject oriented programmingprogramming更新于 2025/2/11 18:20:17

以下正则表达式匹配给定的电子邮件 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})?$";
      //读取用户输入
      Scanner sc = new Scanner(System.in);
      System.out.println("输入您的姓名:");
      String name = sc.nextLine();
      System.out.println("输入您的电子邮件:");
      String e_mail = sc.nextLine();
      System.out.println("输入您的年龄:");
      int age = sc.nextInt();
      //实例化 Pattern 类
      Pattern pattern = Pattern.compile(regex);
      //实例化 Matcher 类
      Matcher matcher = pattern.matcher(e_mail);
      //验证是否发生匹配
      if(matcher.find()) {
         System.out.println("e-mail value accepted");
      } else {
         System.out.println("e-mail not value accepted");
      }
   }
}

Output1

输入您的姓名:
krishna
Enter your e-mail:
Enter your age:
20
e-mail value accepted

输出 2

输入您的姓名:
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

相关文章


有用资源