使用正则表达式检查电子邮件地址是否有效
若要验证给定的输入字符串是否有效的电子邮件 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: [email protected] Given email-id is valid
Output 2
Enter your Email: [email protected] 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: [email protected] Given email id is valid
Output 2
Enter your name: raja Enter your email id: [email protected] Given email id is not valid
从头开始学习 Java,请使用我们的Java 教程。
广告