Monday, March 19, 2012

正規表示法


資料來源:
參考http://caterpillar.onlyfun.net/Gossip/JavaGossip-V1/RegularExpression.htm


當使用 String裡面的matches()、replaceAll()等方法可以使用"正規表示法"進行比較或是替換

以下例子


import java.util.Scanner;
public class UseRegularExpression { 
    public static void main(String args[]) { 
        Scanner scanner = new Scanner(System.in);
 
        String str = "abcdefgabcabc"; 
        System.out.println(str.replaceAll(".bc", "###")); 
 
        System.out.print("輸入手機號碼: "); 
        str = scanner.next();
 
        // 簡單格式驗證 
        if(str.matches("[0-9]{4}-[0-9]{6}")) 
            System.out.println("格式正確"); 
        else 
            System.out.println("格式錯誤");
 
        System.out.print("輸入href標籤: "); 
        // Scanner的next()方法是以空白為區隔
        // 我們的輸入有空白,所以要執行兩次
        str = scanner.next() + " " + scanner.next();
 
        // 驗證href標籤 
        if(str.matches("<a.+href*=*['\"]?.*?['\"]?.*?>"))
            System.out.println("格式正確"); 
        else
            System.out.println("格式錯誤");
 
        System.out.print("輸入電子郵件: "); 
        str = scanner.next();
 
        // 驗證電子郵件格式 
        if(str.matches(
        "^[_a-z0-9-]+([.][_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$"))
            System.out.println("格式正確"); 
        else
            System.out.println("格式錯誤"); 
    } 
} 


執行結果
 ###defg######
 輸入手機號碼: 0988-100432
 格式正確
 輸入href標籤: <a href="http://caterpillar.onlyfun.net">
 格式正確
 輸入電子郵件: justin@caterpillar.onlyfun.net
 格式正確

No comments:

Post a Comment