正則表示式實例1--判斷某個數是不是4的冪數

方法一,直接使用String.matches();

public class TestRegex1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i;
        do{
            System.out.print("輸入:");
            i = scan.nextInt();
            String s = Integer.toBinaryString(i);
            //4的冪數的二進制形式都是以1開頭,後面跟雙數個0
            System.out.println(s.matches("1(00)*"));
        }while(i!=0);
        scan.close();
    }
}

方式二:使用Pattern+Matcher

public class TestRegex1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i;
        Pattern p = Pattern.compile("1(00)*");//編譯正則表達式
        do{
            System.out.print("輸入:");
            i = scan.nextInt();
            String s = Integer.toBinaryString(i);
            //p.matcher(s),獲取Matcher實例,獲取時需要傳入待匹配的字符串,Matcher.maches(),判斷字符串是否符合正則表達式的模式
            System.out.println(p.matcher(s).matches());
        }while(i!=0);
        scan.close();
    }
}

方式一與方式二的比較:

  1. 當比較一次的時候,第一種方式比較簡潔
  2. 當需要多次比較,即用多個字符串匹配一個正則表達式的時候,方式二比較迅速
  3. 一些功能只能由方式二實現,方式一實現不了,如find(),group()等。

    需要注意的是,方式一底層是用方式二實現的:

    public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }
    public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

正則表達式都需要先編譯才能使用。

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