javascript Reg Exp:仅匹配数字和空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8209898/
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-10-26 02:39:30  来源:igfitidea点击:

Reg Exp: match numbers and spaces only

javascriptregex

提问by Claude Dupont

I am writing a js script to validate a form field and I need to check it contains only numbers and possibly whitespace.

我正在编写一个 js 脚本来验证表单字段,我需要检查它是否只包含数字和可能的空格。

What is the regular expression for that?

什么是正则表达式?

回答by jlarsson

You can try something like

你可以尝试类似的东西

var isSpacedNumber = (/^\s*\d+\s*$/i).test(<string value>);

The regular expression consists of the parts

正则表达式由以下部分组成

  • "^" saying that match should start from beginning of input
  • \s* meaning zero or more (*) whitespaces (\s)
  • \d+ meaning one or more (+) digits (\d)
  • \s* meaning zero or more (*) whitespaces (\s)
  • $ meaning match end of string
  • “^”表示匹配应该从输入的开头开始
  • \s* 表示零个或多个 (*) 空格 (\s)
  • \d+ 表示一位或多位 (+) 数字 (\d)
  • \s* 表示零个或多个 (*) 空格 (\s)
  • $ 表示匹配字符串的结尾

Without ^ and $ the regular expression would capture any number in a string, and thus "number is 123" would give positive indication.

如果没有 ^ 和 $ 正则表达式将捕获字符串中的任何数字,因此“数字是 123”将给出肯定的指示。

More information about javascript regular expression can be found here

可以在此处找到有关 javascript 正则表达式的更多信息

回答by Royi Namir

var str = "Watch out for the rock!".match(/^[\d\s]+$/g)

回答by Aziz Shaikh

Try this regular expression:

试试这个正则表达式:

/^[\d\s]+$/

回答by Tim S.

The \dcharacter matches any digit which is the same as using [0-9], the \scharacter matches any whitespace.

\d字符匹配与 using 相同的任何数字[0-9],该\s字符匹配任何空格。

To check if a string is a number (assuming there are no dots or comma's):

要检查字符串是否为数字(假设没有点或逗号):

var regex = /^[\d]+$/;

However, an easier method for you would be to use the isNaN()function. If the function returns true, the number is illegal (NaN). If it returns false, it's a correct number.

但是,对您来说更简单的方法是使用该isNaN()函数。如果函数返回 true,则该数字是非法的 ( NaN)。如果它返回 false,则它是一个正确的数字。

if( !isNaN( value ) ) {
     // The value is a correct number
} else {
     // The value is not a correct number
}