關於java驗證郵箱有效性的填坑記錄

之前項目要驗證email的有效性,由於偷懶在網上抄了一個正則,如下

public static boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";//這個是沒有用的
        Pattern p;
        Matcher m;
        p = Pattern.compile(rule);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }

本以爲網上都是這樣寫的,應該沒事,直到上線才發現問題。

要改成如下這樣才行,上面的是無效的。

public static boolean isEmail(String string) {
		if (string == null)
			return false;
		String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";//這個是沒有用的
		 String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
		Pattern p;
		Matcher m;
		p = Pattern.compile(rule);
		m = p.matcher(string);
		if (m.matches())
			return true;
		else
			return false;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章