正则表达式使用Javascript验证巴西货币 [英] Regex to validate brazilian money using Javascript

查看:115
本文介绍了正则表达式使用Javascript验证巴西货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Javascript验证包含巴西钱(其名称为Real)的一些表单文件。它具有以下格式:

I need to validate some form fileds that contain brazilian money (its name is "Real") using Javascript. It has the following format:

            0,01
            0,12
            1,23
           12,34
          123,45
        1.234,56
       12.235,67
      123.456,78
    1.234.567,89
   12.345.678,90
  123.456.789,01
1.234.567.890,12

我的正则表达式知识很弱,有人可以帮帮我吗?

My regex knowledge is weak, can somebody help me please?

推荐答案

这样做你想要的吗?

^\d{1,3}(?:\.\d{3})*,\d{2}$

这表示1到3位数字,可选地后跟任意数量的三位数组,前面有一个句点,然后是一个逗号和两个以上的数字。如果您想允许示例中的前导空格,请在前面添加 \s *

That says "1 to 3 digits, optionally followed by any number of groups of three digits preceded by a period, followed by a comma and two more digits." If you want to allow the leading whitespace present in your example, add \s* to the front:

^\s*\d{1,3}(?:\.\d{3})*,\d{2}$

编辑:正如@ElRonnoco指出的那样,上面的正则表达式接受前导零(例如010.100,00) )。要禁止这些,您可以使用这个更长的版本:

EDIT: As @ElRonnoco pointed out, the above regular expression accepts leading zeroes (e.g. 010.100,00). To disallow those, you may use this longer version:

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

编辑2 上述正则表达式都匹配包含单个货币金额的字符串,而不包含任何其他内容。从问题中不清楚这是不是意图。

EDIT 2 The above regular expressions all match a string containing a single monetary amount and nothing else. It's not clear from the question if that's the intent.

编辑3 要允许没有小数部分或只有一个十进制数字的数字,改变如下:

EDIT 3 To allow numbers that have no decimal part, or only one decimal digit, change it like this:

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

这篇关于正则表达式使用Javascript验证巴西货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆