方法一,直接使用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();
}
}
方式一與方式二的比較:
- 當比較一次的時候,第一種方式比較簡潔
- 當需要多次比較,即用多個字符串匹配一個正則表達式的時候,方式二比較迅速
一些功能只能由方式二實現,方式一實現不了,如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();
}
正則表達式都需要先編譯才能使用。