2016-11-25 65 views
4

我想爲數字輸入做一個正則表達式模式。當用戶輸入數字時,逗號會自動將輸入的數字分開,如1,424或23,232。這是工作的罰款與正則表達式模式正則表達式的數字用逗號和可選.00

/^[0-9.,]*$/

但問題是,這種模式允許號碼之間的點(。)。我想使正則表達式像輸入可以允許.00在數字之間結束數字。但.00也是可選的。 允許的數量格式如下:

123312131256457.00 
1233121312564 
9,223,372 

不允許號格式如下:

34.343455.3434 
34353... 

我花同樣的失去的時間,但簡化版,得到任何解決方案。請分享你的想法。提前致謝。

回答

0

非常非常簡單的答案是/^[0-9,]*(\.00)?$/。即,添加可選的.00後綴,在可選部分之前刪除對.字符的支持。


如上你評論可以去一些更花哨:^(0|[1-9]\d{0,2}(,?\d{3})*)(\.00)?$

這將表現爲評價:

0 // OK 
01 // Not OK, must start with 1-9 if not 0 or 0.00 
1,1,1.00 // Not OK, groups must be 3 digits, if used 
0,000.00 // Not OK, should be 0.00 
1,000 // OK 
123312131256457.00 // OK, groups are optional 
1233121312564 // OK, decimals (.00) are optional 
9,223,372 // OK 
+0

我的作品。 :-)。非常感謝jensgram – Pooja

+0

這個正則表達式有一個問題:https://www.regex101.com/r/wSPhnv/4 –

+2

它會匹配類似'123,456789.00'的東西,即它匹配有逗號模式的數字。 –

0

只是像

/^[0-9,]*(?:\.0+)?$/ 

[0-9,]*還允許「3 ,,,」

3

試試這個正則表達式:

/^[0-9]{1,3}((,[0-9]{3})*|([0-9])*)(\.[0]{2})?$/ 

這裏是一個簡要說明:

^    from the start 
[0-9]{1,3}  match 1 to 3 numbers 
(,[0-9]{3})* followed by a comma and three numbers, any number of times 
([0-9])*  OR just followed any amount of numbers, with NO commas 
(\.[0-9]{2})? followed by an optional decimal point and two zeroes 
$    end 

演示在這裏:

Regex101

+0

+1我正在擺弄類似的東西。結束於:['^(0 | [1-9] \ d {0,2}(,?\ d {3})*)(\ .00)?$'](http://scriptular.com /#%5E(0%7C%5B1-9%5D%5Cd%7B0%2C2%7D(%2C%3F%5Cd%7B3%7D)*)(%5C.00)%3F%24%7C%7C %7C%7C%7C%7C%7C%7C%5B%220%22%2C%2201%22%2C%221%2C1%2C1.00%22%2C%220%2C000.00%22%2C%221 %2C000%22%2C%22123312131256457.00%22%2C%221233121312564%22%2C%229%2C223%2C372%22%5D) – jensgram