简体   繁体   English

货币的Javascript正则表达式

[英]Javascript regex for currency

I would like to pass only proper currency amounts such as 22.22, 465.56, 1424242.88 我只想传递适当的货币金额,例如22.22、465.56、1424242.88

I have been using this regex: 我一直在使用此正则表达式:

[0-9]+\.[0-9][0-9](?:[^0-9a-zA-Z\s\S\D]|$)

But it allows symbols such as £25.55. 但它允许使用符号,例如£25.55。 How can I force only numbers in correct currency format? 如何只强制采用正确货币格式的数字?

Thanks for any help 谢谢你的帮助

It sounds like you just haven't provided the anchors on the regex, and you haven't escaped the . 听起来您只是没有在正则表达式上提供锚,而您也没有逃脱过. . Eg it should be: 例如,应该是:

var currencyNumbersOnly = /^\d+\.\d{2}$/;

Breakdown: 分解:

  • ^ Start of string. ^字符串的开头。

  • \\d A digit (0-9). \\d一个数字(0-9)。

  • + One or more of the previous entity (and so \\d+ means "one or more digits"). +一个或多个先前的实体(因此\\d+表示“一个或多个数字”)。

  • \\. A literal decimal point. 文字小数点。 Note that some cultures use , rather than . 需要注意的是一些文化使用,而不是. !

  • \\d{2} Exactly two digits. \\d{2}恰好是两位数。

  • $ End of string. $字符串结尾。

This isn't hyper-rigorous. 这不是很严格。 For instance, it allows 0000000.00 . 例如,它允许0000000.00 It also disallows 2 (requiring 2.00 instead). 它还不允许2 (改为2.00 )。 Also note that even when talking about currency figures, we don't always only go down to the hundreds. 还要注意,即使是在谈论货币数据时,我们也不总是总是下降到数百个。 Bank exchange rates, for instance, may go on for several places to the right of the decimal point. 例如,银行汇率可能会在小数点右边连续数个位置。 (For instance, xe.com says that right now, 1 USD = 0.646065 GBP). (例如,xe.com说,现在,1美元= 0.646065英镑)。

And as Jack points out in comments on the question, you may want to allow negative numbers, so throwing a -? 正如杰克(Jack)在对问题的评论中指出的那样,您可能希望允许使用负数,因此请加上-? (0 or 1 - characters) in there after the ^ may be appropriate: (0或1 -字符)在那里之后^可适当:

var currencyNumbersOnly = /^-?\d+\.\d{2}$/;

Update : Now that I can see your full regex, you may want: 更新 :现在,我可以看到您的完整正则表达式,您可能需要:

var currencyNumbersOnly = /^\d+\.\d{2}(?:[^0-9a-zA-Z\s\S\D]|$)/;

I'm not sure what you're doing with that bit at the end, especially as it seems to say (amongst other things) that you allow a single character as long as it isn't 0-9 and as long as it isn't \\D . 我不确定最后您会如何处理,特别是似乎 (除了其他事情)您可以允许一个字符,只要它不是0-9 只要它不是不是\\D As \\D means "not 0-9 ", it's hard to see how something could match that. 因为\\D意思是“不是0-9 ”,所以很难看出有什么能与之匹配。 (And similarly the \\s and \\S in there.) (同样,其中的\\s\\S

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM