使用Javascript无法使RegEx模式在MVC 5 View中正常工作 [英] Can't get RegEx pattern to work correctly in MVC 5 View using Javascript
问题描述
这是我的模式.我正在尝试允许数字和两个位置的小数点以及三个数字的可选逗号.
Here is my pattern. I'm trying to allow numbers and a decimal with two places plus an optional comma with three digits.
var pattern = /^[0-9]+(,\d{3})*\.[0-9]{2}$/;
允许
100,000.12
100,000.12
10,000.12
10,000.12
1,000.12
100.12
10.12
.12(无法允许...请参阅下文)
.12 (can't get this to allow... see below)
不允许
abcd
1,000.12
1,00.12
1,000.0
1,000.
1,000
这是测试.如果我添加一个?在[0-9]之后,它在这里有效,但在我的MVC 5视图中不起作用.该模式不会打开,因此MVC不喜欢它.
Here is the test. If I add a ? after [0-9] it works here, but it does not work in my MVC 5 View. The modal doesn't open, so MVC doesn't like it.
^[0-9]?+(,\d{3})*\.[0-9]{2}$
https://regex101.com/r/HwLS7q/1
更新1
不允许
000,000.12,0.12等...
000,000.12, 0.12 etc...
非常感谢您的帮助!谢谢!
Any help is much appreciated! Thanks!
推荐答案
[0-9]?+
是一种模式,可以完全匹配1或0个数字 允许回溯到模式中.JS正则表达式不支持所有量词,因此问题.
[0-9]?+
is a pattern that matches 1 or 0 digits possessively, not allowing backtracking into the pattern. JS regex does not support possessive quantifiers, hence the issue.
您需要使用
^[0-9]*(?:,[0-9]{3})*\.[0-9]{2}$
或
^(?:[0-9]+(?:,[0-9]{3})*)?\.[0-9]{2}$
在这里, [0-9] *
匹配零个或多个数字,并且(?:[0-9] +(?:,[0-9] {3})*)?
匹配一个可选的1+位数字序列,后跟0+个重复的,
和3位数字组.
Here, the [0-9]*
match zero or more digits and (?:[0-9]+(?:,[0-9]{3})*)?
matches an optional sequence of 1+ digits followed with 0+ repetitions of ,
and 3 digit groups.
请参见此regex演示.
更精确的模式是将第一位数字块限制为1位,2位或3位数字,并使整数部分为可选:
A more precise pattern would be to restrict the first digit chunk to 1, 2 or 3 digits and make the integer part optional:
^(?:[0-9]{1,3}(?:,[0-9]{3})*)?\.[0-9]{2}$
请参见 regex演示.
详细信息
-
^
-字符串的开头 -
(?:[0-9] {1,3}(?:,[0-9] {3})*)?
-的可选序列-
[0-9] {1,3}
-1-3位数字 -
(?:,[0-9] {3})*
-重复0次或更多次-
,
-逗号 -
[0-9] {3}
-三位数
^
- start of string(?:[0-9]{1,3}(?:,[0-9]{3})*)?
- an optional sequence of[0-9]{1,3}
- one to three digits(?:,[0-9]{3})*
- 0 or more repetitions of,
- comma[0-9]{3}
- three digits
这篇关于使用Javascript无法使RegEx模式在MVC 5 View中正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-
-