简体   繁体   English

RegEx货币(JavaScript)

[英]RegEx for currency (JavaScript)

I am new to regular expressions and i would like to validate user input with javascript. 我是正则表达式的新手,我想用javascript验证用户输入。

The user input is a currency, but i want it without the thousands commata. 用户输入是一种货币,但我希望它没有数千个逗号。

Valid 有效

"12.34"
"12,34"
"1234,5"
"123"
"123,00"
"12000"

Invalid 无效

"12a34"
"abc"
"12.000,00"
"12,000.00"

I tried the following regex-pattern, but it doesnt work for me. 我尝试了以下正则表达式模式,但它对我不起作用。 it validates for example "12a34" and i dont know why. 它验证例如“12a34”,我不知道为什么。

/\d+([\.|\,]\d+)?/

What would be the correct regex-pattern ? 什么是正确的正则表达式模式? Could you explain this step by step ? 你能一步一步地解释一下吗?

Thanks ! 谢谢 !

Do not escape the . 别逃避了. while in a character group. 而在一个角色组。 Try with following regex: 尝试使用以下正则表达式:

/^\d+([.,]\d{1,2})?$/

^   = start of string
$   = end of string
()? = an optional capturegroup ( e.g. to validate "123")
{x,y} = The symbol may occur minimum x and maximum y times
RegExp: /^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$/g
pattern: ^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$
flags: g
3 capturing groups: 
   group 1: (0|[1-9]\d{0,2}(,?\d{3})?)
   group 2: (,?\d{3})
   group 3: (\.\d\d?)

Regex Test 正则表达式测试

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

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