Regex number amount validation

佐手、 提交于 2021-02-11 07:40:27

问题


I want to validate the amount with the below scenario. The below regex is working except ',' for example 1,000.0000

^(?!0*(\.0+)?$)(\d*(?:\.[0-9]{0,4})?)$

1 - should pass
0.1 - should pass
.1 - should pass
0 - should fail
.0001 - should pass
.10 - should pass
0.0  - should fail
0.00000 - should fail (only accept 4 digits after the decimal point)
1.0000 - should pass
1,000.0000 - should pass
1,000,00.000 - should pass
1,000.0000 - should pass

回答1:


^(?![0,]*(\.0+)?$)([,\d]*(?:\.[0-9]{0,4})?)$. I simply replaced the \d before the decimal separator with [,\d]; and also in the negative assertion, so that 0,000.00 doesn't match. It allows any number of commas placed everywhere, and this is reasonable, because local traditions of grouping digits differ.

Also, do you want numbers with hanging dots, like 10. to match? If not, replace {0,4} with {1,4}. https://regex101.com/r/XB8OtL/3.




回答2:


Changing the last ? (zero or one repetition) with a * (any number of repetitions) (so ^(?!0*(.0+)?$)(\d*(?:.[0-9]{0,4})*)$) will validate the inputs that should validate (it's the repetition of the ,000 or .000 that fails the test). By the way your regex could be improved: because you use . (any character) instead of \. (dot) or ',' coma, your regex ie validate bad inputs like '1x0000' or '1#0000' (any character)



来源:https://stackoverflow.com/questions/64385300/regex-number-amount-validation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!