Javascript regexp 检查输入是否只是整数 (int) ,并检查另一个是否只有 2 个小数位的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8144526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:52:13  来源:igfitidea点击:

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

javascriptregex

提问by re1man

I want to know what a regex would look like for:

我想知道正则表达式的样子:

  1. only whole numbers
  2. only numbers with less than or equal to two decimal places (23, 23.3, 23.43)
  1. 只有整数
  2. 只有小于或等于两位小数的数字 (23, 23.3, 23.43)

回答by NullUserException

Only whole numbers:

只有整数:

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

Numbers with at most 2 decimal places:

最多保留 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

Notes:

笔记:

  • The slashes denote start and end of pattern
  • ^and $are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/matches '398501', but it also matches 'abc123'. The anchors ensures the entirestring matches the given pattern.
  • If you want to allow negative numbers, add a -?before the first \d. Again, ?denotes "zero or one time."
  • 斜线表示模式的开始和结束
  • ^$是字符串锚点的开始和结束。如果没有这些,它将在字符串中的任何位置查找匹配项。所以/\d+/匹配'398501',但它也匹配'abc123'。锚点确保整个字符串匹配给定的模式。
  • 如果要允许负数,请-?在第一个\d. 再次?表示“零次或一次”。


Usage example:

用法示例:

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

回答by toon81

I. [1-9][0-9]*if the number should be greater than zero (any series of digits starting with a nonzero digit). if it should be zero or more: (0|[1-9][0-9]*)(zero or a nonzero number). If it can be negative: (0|-?[1-9][0-9]*)(zero or a nonzero number that can have a minus before it.)

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

II. a regex like I. followed by: (\.[0-9]{1,2})?that means, optionally a dot followed by one or two digits.

二、像 I. 一样的正则表达式。后跟:(\.[0-9]{1,2})?这意味着,可以选择一个点后跟一位或两位数字。

回答by Alex Peattie

Whole numbers only

仅限整数

/\d+/

One or two decimal places:

一位或两位小数:

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