简体   繁体   English

正则表达式,JavaScript中输入字符串中包含可选元素

[英]Regular Expression with optional elements in input string in javascript

Can anyone give me the regular expression for currency which have the following formats : 任何人都可以给我货币的正则表达式,其格式如下:

1000 - valid
1,000 - valid
1,000.00 or 1000.00 - valid.

This means, the number May or May Not contain a comma(,) separator every 3 digits. 这意味着数字“ 可能”或“可能不”每三位数包含一个逗号分隔符。

The number May Or May Not contain a dot (.), and if it carries a dot(.) it should show atleast 1 number after the decimal place. 该数字可能不包含点(。),并且如果它带有点(。),则应在小数点后显示至少1个数字。

And lastly it should be numerical characters only. 最后,它只能是数字字符。 If I need to make my question clear kindly suggest. 如果我需要澄清我的问题,请提出。

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

"Between one and three digits, then any number of groups of three digits prefixed by a comma or any number of groups of three digits not prefixed by said comma (disallowing a mix of the two kinds of groups), then an optional group of one or two digits prefixed by a dot." “在一位数字和三位数字之间,然后是任意数量的以逗号为前缀的三位数的组, 或者是任意数量的没有以逗号为前缀的三位数的组(不允许这两种组的混合),然后是一个可选的一组或以小数点开头的两位数字。”

Note: This regex assumes that you want to validate an entire string against the criteria outlined in your question. 注意:此正则表达式假定您要根据问题中概述的条件来验证整个字符串。 If you want to use it to find such numbers in a longer string, you will need to remove the ^ and $ from the beginning and end of the expression. 如果要使用它在较长的字符串中查找此类数字,则需要从表达式的开头和结尾删除^$

Something like so should work: (,?\\d{3})+(\\.\\d{2})? 像这样的东西应该起作用: (,?\\d{3})+(\\.\\d{2})? . The regex will attempt to match a sequence of 3 digits precedeed by an optional comma, which is then, finally followed by an optional decimal point and 2 digits. 正则表达式将尝试匹配一个3位数的序列,其后是一个可选的逗号,然后是逗号,最后是一个可选的小数点和2位数字。

Please refer to this tutorial for more information. 请参考教程以获取更多信息。

EDIT: As per the comment below, the above regex can fail. 编辑:根据下面的评论,上述正则表达式可能会失败。 I would recommend first using this regular expression: ^[\\d][\\d.,]+$ to make sure that you only have digits, thousand and decimal seperators. 我建议首先使用以下正则表达式: ^[\\d][\\d.,]+$ ,以确保您只有数字,千位和十进制分隔符。 This regular expression will also make sure that the number starts with a digit, not with anything else. 此正则表达式还将确保数字以数字开头,而不以其他任何内容开头。 You could most likely have one regular expression which does everything, but it will most likely be quite complex. 您很可能拥有一个可以执行所有操作的正则表达式,但是它很可能非常复杂。

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

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