gpt4 book ai didi

javascript - 数字和一位小数的正则表达式

转载 作者:行者123 更新时间:2023-12-01 01:56:58 26 4
gpt4 key购买 nike

我似乎无法使用简单的正则表达式来工作。这是我目前所拥有的:

$(".Hours").on('input', function (e) {

var regex = /^\d+(\.\d{0,2})?$/g;

if (!regex.test(this.value)) {
if (!regex.test(this.value[0]))
this.value = this.value.substring(1, this.value.length);
else
this.value = this.value.substring(0, this.value.length - 1);
}
});

我需要用户只能输入数字和一位小数(小数点后只有两位数字)。现在工作正常,只是用户不能以小数开头。

可接受:

23.53
0.43
1111.43
54335.34
235.23
.53 <--- Not working

Not Acceptable :

0234.32 <--- The user can currently do this
23.453
1.343
.234.23
1.453.23

对此有什么帮助吗?

最佳答案

更新的答案:

正则表达式-

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

解释位于regex101 :

enter image description here

原始答案:

fiddle Demo

正则表达式-

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

说明

Assert position at the beginning of the string «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regular expression below and capture its match into backreference number 2 «([.]?\d{0,2})?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character “.” «[.]?»
Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match a single digit 0..9 «\d{0,2}»
Between zero and 2 times, as many times as possible, giving back as needed (greedy) «{0,2}»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»

关于javascript - 数字和一位小数的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20050245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com