gpt4 book ai didi

javascript - 十进制数的正则表达式接受 0 到 4 位数字但没有字符

转载 作者:行者123 更新时间:2023-11-29 18:06:39 30 4
gpt4 key购买 nike

我正在尝试设计一个正则表达式,它可以接受最多 4 位的十进制数。当用户在文本框中键入时,我已经成功完成了。现在,我正在尝试验证 paste 操作的文本框。为此,我编写了一个jquery 函数

 function pasteNumber() {
var reNumber = /\d*\.\d{0,4}/;
var theString = window.clipboardData.getData('Text');

if (reNumber.test(theString) == false) {
alert("You are trying to paste an invalid Number!")
return;
}
event.srcElement.value = theString
return;
}

我使用的正则表达式接受一个值,如

44.aaaa

它不应该接受。然后我尝试将正则表达式更改为

/\d*\.\d{1,4}/

然后,它开始接受这样的值

44.1aaa

我需要帮助来编写一个接受值的正则表达式

4.1
421.11
467.111
438904.1111
0.1

但不是

1234.a
489.a
435.aaa
412.1aaaa
1567.11a

简而言之,应该没有字符。

有什么建议吗?谢谢

最佳答案

您只缺少 anchor ^$

^\d*\.\d{0,4}$

参见 demo

但是,为了避免匹配 .123.,您可以将其增强为

^\d*\.\d{1,4}$

参见 update .

As for anchors , 他们

do not match any character at all. Instead, they match a position before, after, or between characters. They can be used to anchor the regex match at a certain position. The caret ^ matches the position before the first character in the string. Applying ^a to abc matches a. ^b does not match abc at all, because the b cannot be matched right after the start of the string, matched by ^.

Similarly, $ matches right after the last character in the string. c$ matches c in abc, while a$ does not match at all.

关于javascript - 十进制数的正则表达式接受 0 到 4 位数字但没有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730877/

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