2013-03-11 141 views
0

我對正則表達式相當陌生,而且我有時間獲得一個我制定的正確表達式。以下是我所制定的表達方式。數字大於浮點數

^((?!^1[0-6]*\.?[0-2][0-4]+)^(\d+))$ 

我想建立一個表達式來驗證一個大於16.24的數字。輸入需要能夠接受像17這樣的整數,而不需要用戶輸入17.00來驗證。任何想法我做錯了什麼?

+5

這不是很好用的正則表達式。只需從字符串轉換爲適當的數字數據類型,然後執行數字比較。 – 2013-03-11 00:50:06

+0

@thebradnet數字隱藏在字符串中嗎? – 2013-03-11 00:52:48

回答

1

你可以這樣做的一種方法是使用正則表達式來提取數值,然後將它們解析爲一個數字並將它們與期望的常量進行比較。

的Javascript:代碼示例

編號爲字符串:

var test = function(str){ 
    return 16.24 < parseFloat(str); 
}; 
console.log(test("234.23") == true); // true 
console.log(test("-234.23") == false); // true 

號碼隱藏與其他字符的字符串中。

var test = function (str) { 
    var re, 
    num; 

    if (/[eE]/.test(str)) { 
     // search for scientific numbers 
     re = /-?\d+(\.\d+)?[eE]\d+/; 
    } else { 
     // search for whole or decimal numbers 
     re = /-?\d+(\.\d{1,2})?/; 
    } 
    num = str.match(re); 
    return 16.24 < parseFloat(num); 
}; 
console.log(test("input = 234.23") == true); // true 
console.log(test("input = 2e34") == true); // true 
console.log(test("input = -2e34") == false); // true 
console.log(test("input = -234.23") == false); // true 
+0

除了不會找到象「1.623e1」這樣的陳述... – 2013-03-11 01:15:31

+0

@OliCharlesworth謝謝。我更新了代碼。 – 2013-03-11 01:59:14

+0

你的第一個建議工作。我一直被這樣做成正則表達式,以至於我忘了以另一種方式做這件事。 – thebradnet 2013-03-11 03:45:11