我想通過使用正則表達式來檢測String
是否爲小數。我的問題是關於如何使用正則表達式機制,而不是檢測String
是小數。我使用GWT
提供的RegExp
類。RegExp GWT/Javascript的測試方法
String regexDecimal = "\\d+(?:\\.\\d+)?";
RegExp regex = RegExp.compile(regexDecimal);
String[] decimals = { "one", "+2", "-2", ".4", "-.4", ".5", "2.5" };
for (int i = 0; i < decimals.length; i++) {
System.out.println(decimals[i] + " "
+ decimals[i].matches(regexDecimal) + " "
+ regex.test(decimals[i]) + " "
+ regex.exec(decimals[i]));
}
輸出:
one false false null
+2 false true 2
-2 false true 2
.4 false true 4
-.4 false true 4
.5 false true 5
2.5 true true 2.5
我期待這兩種方法String.matches()
和RegExp.test()
返回相同的結果。
- 那麼 這兩種方法有什麼區別?
- 如何使用
RegExp.test()
獲得相同的行爲?
這兩個答案都很好,並解決了我的問題,所以現在哪一個我接受,因爲他們基本上是相同的答案? – Sydney 2011-05-14 12:25:41