本文實例講述了java使用正則表達式判斷郵箱格式是否正確的方法。分享給大家供大家參考。具體如下:
import java.io.*;public class CheckEmail { public static boolean checkEmail(String email) {// 驗證郵箱的正則表達式 String format = "http://p{Alpha}//w{2,15}[@][a-z0-9]{3,}[.]//p{Lower}{2,}"; //p{Alpha}:內容是必選的,和字母字符[/p{Lower}/p{Upper}]等價。如:200896@163.com不是合法的。 //w{2,15}: 2~15個[a-zA-Z_0-9]字符;w{}內容是必選的。 如:dyh@152.com是合法的。 //[a-z0-9]{3,}:至少三個[a-z0-9]字符,[]內的是必選的;如:dyh200896@16.com是不合法的。 //[.]:'.'號時必選的; 如:dyh200896@163com是不合法的。 //p{Lower}{2,}小寫字母,兩個以上。如:dyh200896@163.c是不合法的。 if (email.matches(format)) { return true;// 郵箱名合法,返回true } else { return false;// 郵箱名不合法,返回false } } public static void main(String[] args) throws Exception { String email = "cc**365@163.com"; // 需要進行驗證的郵箱 while(true) { email = new BufferedReader(new InputStreamReader(System.in)).readLine(); if (CheckEmail.checkEmail(email))// 驗證郵箱 { System.out.println(email+"/n是合法的郵箱名。"); } else { System.out.println(email+"/n不是合法的郵箱名。"); } } }}
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.VeVB.COm/regex/javascript
正則表達式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
希望本文所述對大家的java程序設計有所幫助。
新聞熱點
疑難解答