regex to allow decimals, but no commas

落爺英雄遲暮 提交于 2019-12-08 10:02:29

问题


I need a regex expression that allows decimals but no commas. Such as: 1200.00 or 50.00
or 40 or 1 The expression is used in a validation to make sure people put in a price as a number, but no commas. I currently have a regex that allows for commas, numbers, and decimals, but I cannot seem to get the commas out.

This is the current regex that I have which doesnt allow commas or decimals, but I want decimals in there

/^[0-9\ ]+$/,

Thanks for your help.


回答1:


Something like this should work: ^\d+(\.\d{2})?$

This basically states the following:

  • ^\d+: Start from the beginning of the string (^) and match one or more digits (\d+).
  • (\.\d{2})?: Match a period character (\.) followed by exactly 2 digits (\d{2}). The question mark denotes that the value within the brackets can either exist or not, meaning that it will match either 1 or 0 instances of the pattern.
  • $: The string must end here.



回答2:


To match the currency you can use this regex

^(?:[1-9]\d+|\d)(?:\.\d\d)?$



回答3:


You probably forgot to escape the regex . operator (which means match any character). Only guessing since you forgot an important piece of information in your question: the failing regexes you have already tried!




回答4:


Allow 0 or 1 dots, with only digits before and after...

/^\d*\.{0,1}\d*$/


来源:https://stackoverflow.com/questions/10169147/regex-to-allow-decimals-but-no-commas

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