我花了好几个小时来寻找解决方案。我有以下RegEx:
(?=.)^(([1-9][0-9]{0,8})|([0-9]))?(\.[0-9]{1,2})?$
我想添加第一个字符匹配减号的功能,但仍然与所述RegEx的其余部分匹配。
I need these to work: .0 .34 -.34 -30.0 -33.03 -34 -2 I need these to fail: -04.4 043 3. - $34.33 1234567890.23 (any non-numeric character)
感谢您的协助。
答案 0 :(得分:3)
您可以使用此正则表达式:
^-?(?:[1-9][0-9]{0,8}(?:\.[0-9]{1,2})?|\.[0-9]{1,2})$
编辑:如果您想允许0.45
作为有效输入,请使用:
^-?(?:[1-9][0-9]{0,8}(?:\.[0-9]{1,2})?|0*\.[0-9]{1,2})$
答案 1 :(得分:0)
在正确的位置添加可选的-?
应该可以解决问题。
此外,我相当确定您不需要所有这些捕获组(请参阅demo here):
^-?(?=.)(?:[1-9][0-9]{0,8}|0)?(?:\.[0-9]{1,2})?$
^-? # optional leading -
(?=.) # followed by at least one character
(?: # non capturing group
[1-9][0-9]{0,8} # number without leading 0
| # or
0 # single 0
)? # integer part is optional
(?:\.[0-9]{1,2})?$ # decimal part
答案 2 :(得分:0)