正則表達式--Java郵箱驗證


主要使用Pattern與Matcher類來執行正則表達式運算

Pattern是用於編譯正則表達式,通過complie方法返回一個pattern對象

    /**
     * Compiles the given regular expression into a pattern.
     *
     * @param  regex  正則表達式
     *         The expression to be compiled
     * @return the given regular expression compiled into a pattern
     * @throws  PatternSyntaxException
     *          If the expression's syntax is invalid
     */
    public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
    }

 Matcher用於匹配正則表達式

首先通過Pattern獲取一個Mathcer, 參數是要驗證的字符串

matcher=pattern.matcher(reader.nextLine());

獲得Mathcer對象后可利用它的matches等方法查看驗證結果

 

 

Java實現的匹配郵箱

package regex;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
    private static String regex;
    private static Pattern pattern;
    private static Matcher matcher;
    public static void main(String argv[]){
        Scanner reader=new Scanner(System.in);
        //查找郵箱
        //mailRegex是整體郵箱正則表達式,mailName是@前面的名稱部分,mailDomain是后面的域名部分
        String mailRegex,mailName,mailDomain;
        mailName="^[0-9a-z]+\\w*";       //^表明一行以什么開頭;^[0-9a-z]表明要以數字或小寫字母開頭;\\w*表明匹配任意個大寫小寫字母或數字或下划線
        mailDomain="([0-9a-z]+\\.)+[0-9a-z]+$";       //***.***.***格式的域名,其中*為小寫字母或數字;第一個括號代表有至少一個***.匹配單元,而[0-9a-z]$表明以小寫字母或數字結尾
        mailRegex=mailName+"@"+mailDomain;          //郵箱正則表達式      ^[0-9a-z]+\w*@([0-9a-z]+\.)+[0-9a-z]+$
        pattern=Pattern.compile(mailRegex);
        matcher=pattern.matcher(reader.nextLine());
        if(matcher.matches()){
            System.out.println("found");
        }else {
            System.out.println("not found");
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM