因此,我必須撰寫一個正則運算式陳述句來證明一個數字是否可被 5 整除并回傳真或假。因此,經過一些研究,我發現任何以 0 或 5 結尾的數字都可以被 5 整除,因此我嘗試將字串的最后一位數字與 0 或 5 匹配。
但是,它似乎不起作用,因為該方法只回傳 false,盡管它適用于在線正則運算式檢查器。
public class MyClass {
public static void main(String args[]) {
String[] digits = {"20", "25", "000", "001", "5123456789"};
for (String s : digits){
System.out.println("\"" s "\"" " -> " proof(s));
}
}
public static boolean proof(String s){
return s.matches("[0|5]$"); // Here is somehow an issue.
}
}
uj5u.com熱心網友回復:
這是實作此功能的一種可能方法:
public static boolean proof(String s) {
return s.matches("([1-9]\\d*)?[05]");
}
where([1-9]\\d*)?匹配一個可選的字符組(即它可能不存在),它應該以一個數字 from 1to開頭,9后跟零個或多個數字。
筆記
'|'不需要管道符號。當你使用方括號[]時,你只需要列舉你需要匹配的符號,即[05]。雖然使用
matches()正則運算式將應用于整個字串,即既不需要也不需要^最開始,不需要$最后不需要。免責宣告:在我對問題陳述的解釋中,不允許使用前導零。如果此要求不相關,則以下正則運算式就足夠了:
"\\d*[05]".
為了避免在每次方法呼叫時編譯這個正則運算式,我們可以將它提取到static final欄位中。并且由于您需要一個boolean結果,因此將其保存為 a 會很方便Predicate,因為我們可以使用 Java 11Pattern.asMatchPredicate()
public static final Predicate<String> IS_DIVISIBLE_BY_FIVE =
Pattern.compile("([1-9]\\d*)?[05]").asMatchPredicate();
public static boolean proof(String s) {
return IS_DIVISIBLE_BY_FIVE.test(s);
}
main()
public static void main(String[] args) {
String[] digits = {"20", "25", "000", "001", "5123456789"};
for (String number : digits) {
System.out.println(number " -> " proof(number));
}
}
輸出:
20 -> true
25 -> true
000 -> false
001 -> false
5123456789 -> false
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527818.html
標籤:爪哇正则表达式细绳
