gpt4 book ai didi

javascript - 正则表达式检查输入是否只是整数 (int) ,并检查另一个是否只是带有 2 个小数位的数字

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:53 24 4
gpt4 key购买 nike

我想知道正则表达式的用途:

  1. 只有整数
  2. 仅小于或等于小数点后两位的数字(23、23.3、23.43)

最佳答案

只有整数:

/^\d+$/
# explanation
\d match a digit
+ one or more times

最多保留 2 位小数的数字:

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

# explanation
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional

注意事项:

  • 斜杠表示模式的开始和结束
  • ^$ 是字符串 anchor 的开始和结束。如果没有这些,它将在字符串中的任何位置寻找匹配项。所以 /\d+/ 匹配 '398501',但它也匹配 'abc123'。 anchor 确保整个字符串匹配给定的模式。
  • 如果要允许负数,请在第一个\d 之前添加一个-?。同样,? 表示“零次或一次”。

使用示例:

var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc')); // false
console.log(rx.test('309')); // true
console.log(rx.test('30.9')); // true
console.log(rx.test('30.85')); // true
console.log(rx.test('30.8573')); // false

关于javascript - 正则表达式检查输入是否只是整数 (int) ,并检查另一个是否只是带有 2 个小数位的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8144526/

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