2014-08-31 161 views
0

我試圖匹配數字模式。前兩位數字將是25。可能有更多數字,例如252532599255模式匹配不匹配

爲此,我已經寫了像

Pattern myPattern = Pattern.compile("[2][5]*"); 
if(myPattern.matcher("25").matches()) { 
} 

if(myPattern.matcher("253").matches()) { 
} 

但它總是返回false。我不確定我的模式有什麼問題。

回答

2

你可以試試下面的正則表達式,

"25\\d*" 

有什麼不對您正則表達式[2][5]*,首先它匹配2那麼它只有5號零次或多次匹配。但是\d*與任何數字(0-9)零次或多次匹配。

System.out.println("25".matches("25\\d*")); 
System.out.println("253".matches("25\\d*")); 
1

嘗試用

String.matches("25\\d*") 

enter image description here

或者你CAU使用

String.startsWith("25") 
3

雖然你可以通過使用@avinashraj建議的正則表達式解決這個問題,我想建議使用String#startsWith更好的解決方案,你並不需要這裏的正則表達式:

if(myString.startsWith("25")) { 
    //... 
}