Regexp用于检查输入是否仅为整数(int),以及检查另一个输入是否仅为带有2位小数的数字

regexp to check if input is only whole numbers (int) , and to check if another is only numbers with 2 decimal places

本文关键字:是否 输入 检查 另一个 2位 小数 数字 整数 用于 int Regexp      更新时间:2023-09-26

我想知道一个正则表达式是什么样子的:

  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

指出:

  • 斜杠表示模式的开始和结束
  • ^$是字符串锚点的开始和结束。如果没有这些,它将在字符串的任何地方寻找匹配。所以/'d+/'398501'匹配,但也和'abc123'匹配。锚确保整个字符串匹配给定的模式。
  • 如果您希望允许负数,请在第一个'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

如果数字应该大于零(以非零数字开头的任何数字序列),则[1-9][0-9]*。如果它应该是零或更多:(0|[1-9][0-9]*)(零或非零数字)。如果是负数:(0|-?[1-9][0-9]*)(0或前面可以有负号的非0数)

二世。像i这样的正则表达式,后面跟着:('.[0-9]{1,2})?,表示可选的点后面跟着一个或两个数字。

仅限整数

/'d+/

小数点后一位或两位:

/'d('.'d{1,2})?/