Javascript 正则表达式检查字符串是否只包含数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9011524/
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
Regex to check whether a string contains only numbers
提问by Johan
hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));
I get false on both "123"
and "123f"
. I would like to check if the hash only contains numbers. Did I miss something?
我在"123"
和上都出错了"123f"
。我想检查散列是否只包含数字。我错过了什么?
回答by Mike Samuel
var reg = /^\d+$/;
should do it. The original matches anything that consists of exactly one digit.
应该这样做。原始匹配任何由一位数字组成的内容。
回答by Abhijeet Rastogi
As you said, you want hash to contain only numbers.
正如您所说,您希望哈希仅包含数字。
var reg = new RegExp('^[0-9]+$');
or
或者
var reg = new RegExp('^\d+$');
\d
and [0-9]
both mean the same thing.
The + used means that search for one or more occurring of [0-9].
\d
并且[0-9]
两者都是同一个意思。使用的 + 表示搜索 [0-9] 中的一个或多个出现。
回答by codename-
This one will allow also for signed and float numbers or empty string:
这也将允许签名和浮点数或空字符串:
var reg = /^-?\d*\.?\d*$/
If you don't want allow to empty string use this one:
如果你不想允许空字符串使用这个:
var reg = /^-?\d+\.?\d*$/
回答by Dastagir
var validation = {
isEmailAddress:function(str) {
var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return pattern.test(str); // returns a boolean
},
isNotEmpty:function (str) {
var pattern =/\S+/;
return pattern.test(str); // returns a boolean
},
isNumber:function(str) {
var pattern = /^\d+$/;
return pattern.test(str); // returns a boolean
},
isSame:function(str1,str2){
return str1 === str2;
}
};
alert(validation.isNotEmpty("dff"));
alert(validation.isNumber(44));
alert(validation.isEmailAddress("[email protected]"));
alert(validation.isSame("sf","sf"));
回答by David Leppik
This is extreme overkill for your purpose, but here's what I use:
这对您的目的来说是极端的矫枉过正,但这是我使用的:
var numberReSnippet = "(?:NaN|-?(?:(?:\d+|\d*\.\d+)(?:[E|e][+|-]?\d+)?|Infinity))";
var matchOnlyNumberRe = new RegExp("^("+ numberReSnippet + ")$");
To my knowledge, this matches all the variations on numbers that Java and JavaScript will ever throw at you, including "-Infinity", "1e-24" and "NaN". It also matches numbers you might type, such as "-.5".
据我所知,这与 Java 和 JavaScript 将向您抛出的所有数字变化相匹配,包括“-Infinity”、“1e-24”和“NaN”。它还匹配您可能键入的数字,例如“-.5”。
As written, reSnippet is designed to be dropped into other regular expressions, so you can extract (or avoid) numbers. Despite all the parentheses, it contains no capturing groups. Thus "matchOnlyNumberRe" matches only strings that are numbers, and has a capturing group for the entire string.
正如所写的那样,reSnippet 旨在放入其他正则表达式中,因此您可以提取(或避免)数字。尽管有所有括号,但它不包含捕获组。因此,“matchOnlyNumberRe”仅匹配数字字符串,并且具有整个字符串的捕获组。
Here are the Jasmine tests, so you can see what it does and doesn't handle:
下面是 Jasmine 测试,所以你可以看到它做什么和不处理什么:
describe("Number Regex", function() {
var re = new RegExp("^("+ numberReSnippet + ")$");
it("Matches Java and JavaScript numbers", function() {
expect(re.test( "1")).toBe(true);
expect(re.test( "0.2")).toBe(true);
expect(re.test( "0.4E4")).toBe(true); // Java-style
expect(re.test( "-55")).toBe(true);
expect(re.test( "-0.6")).toBe(true);
expect(re.test( "-0.77E77")).toBe(true);
expect(re.test( "88E8")).toBe(true);
expect(re.test( "NaN")).toBe(true);
expect(re.test( "Infinity")).toBe(true);
expect(re.test( "-Infinity")).toBe(true);
expect(re.test( "1e+24")).toBe(true); // JavaScript-style
});
it("Matches fractions with a leading decimal point", function() {
expect(re.test( ".3")).toBe(true);
expect(re.test( "-.3")).toBe(true);
expect(re.test( ".3e-4")).toBe(true);
});
it("Doesn't match non-numbers", function() {
expect(re.test( ".")).toBe(false);
expect(re.test( "9.")).toBe(false);
expect(re.test( "")).toBe(false);
expect(re.test( "E")).toBe(false);
expect(re.test( "e24")).toBe(false);
expect(re.test( "1e+24.5")).toBe(false);
expect(re.test("-.Infinity")).toBe(false);
});
});
回答by user1299656
^[0-9]$
...is a regular expression matching any single digit, so 1 will return true but 123 will return false.
...是匹配任何单个数字的正则表达式,因此 1 将返回 true 但 123 将返回 false。
If you add the * quantifier,
如果添加 * 量词,
^[0-9]*$
the expression will match arbitrary length strings of digits and 123 will return true. (123f will still return false).
该表达式将匹配任意长度的数字字符串,123 将返回 true。(123f 仍然会返回 false)。
Be aware that technically an empty string is a 0-length string of digits, and so it will return true using ^[0-9]*$ If you want to only accept strings containing 1 or more digits, use + instead of *
请注意,从技术上讲,空字符串是一个长度为 0 的数字字符串,因此它将使用 ^[0-9]*$ 返回 true 如果您只想接受包含 1 个或多个数字的字符串,请使用 + 而不是 *
^[0-9]+$
As the many others have pointed out, there are more than a few ways to achieve this, but I felt like it was appropriate to point out that the code in the original question only requires a single additional character to work as intended.
正如许多其他人指出的那样,有很多方法可以实现这一点,但我觉得指出原始问题中的代码只需要一个额外的字符即可按预期工作是合适的。
回答by Juan Lanus
This function checks if it's input is numeric in the classical sense, as one expects a normal number detection function to work.
这个函数检查它的输入是否是经典意义上的数字,因为人们期望正常的数字检测函数可以工作。
It's a test one can use for HTML form input, for example.
例如,这是一个可用于 HTML 表单输入的测试。
It bypasses all the JS folklore, like tipeof(NaN) = number, parseint('1 Kg') = 1, booleans coerced into numbers, and the like.
它绕过了所有 JS 民间传说,例如 tipeof(NaN) = number、parseint('1 Kg') = 1、布尔值强制转换为数字等。
It does it by rendering the argument as a string and checking that string against a regex like those by @codename- but allowing entries like 5. and .5
它通过将参数呈现为字符串并根据@codename- 之类的正则表达式检查该字符串来实现,但允许像 5. 和 .5 这样的条目
function isANumber( n ) {
var numStr = /^-?(\d+\.?\d*)$|(\d*\.?\d+)$/;
return numStr.test( n.toString() );
}
not numeric:
Logger.log( 'isANumber( "aaa" ): ' + isANumber( 'aaa' ) );
Logger.log( 'isANumber( "" ): ' + isANumber( '' ) );
Logger.log( 'isANumber( "lkjh" ): ' + isANumber( 'lkjh' ) );
Logger.log( 'isANumber( 0/0 ): ' + isANumber( 0 / 0 ) );
Logger.log( 'isANumber( 1/0 ): ' + isANumber( 1 / 0 ) );
Logger.log( 'isANumber( "1Kg" ): ' + isANumber( '1Kg' ) );
Logger.log( 'isANumber( "1 Kg" ): ' + isANumber( '1 Kg' ) );
Logger.log( 'isANumber( false ): ' + isANumber( false ) );
Logger.log( 'isANumber( true ): ' + isANumber( true ) );
numeric:
Logger.log( 'isANumber( "0" ): ' + isANumber( '0' ) );
Logger.log( 'isANumber( "12.5" ): ' + isANumber( '12.5' ) );
Logger.log( 'isANumber( ".5" ): ' + isANumber( '.5' ) );
Logger.log( 'isANumber( "5." ): ' + isANumber( '5.' ) );
Logger.log( 'isANumber( "-5" ): ' + isANumber( '-5' ) );
Logger.log( 'isANumber( "-5." ): ' + isANumber( '-5.' ) );
Logger.log( 'isANumber( "-.5" ): ' + isANumber( '-5.' ) );
Logger.log( 'isANumber( "1234567890" ): ' + isANumber( '1234567890' ));
Explanation of the regex:
正则表达式的解释:
/^-?(\d+\.?\d*)$|(\d*\.?\d+)$/
The initial "^" and the final "$" match the start and the end of the string, to ensure the check spans the whole string. The "-?" part is the minus sign with the "?" multiplier that allows zero or one instance of it.
开头的“^”和结尾的“$”匹配字符串的开头和结尾,以确保检查跨越整个字符串。这 ”-?” 部分是带有“?”的减号 允许零个或一个实例的乘数。
Then there are two similar groups, delimited by parenthesis. The string has to match either of these groups. The first matches numbers like 5. and the second .5
然后有两个相似的组,由括号分隔。该字符串必须匹配这些组中的任何一个。第一个匹配像 5. 和第二个 .5 这样的数字
The first group is
第一组是
\d+\.?\d*
The "\d+" matches a digit (\d) one or more times.
The "\.?" is the decimal point (escaped with "\" to devoid it of its magic), zero or one times.
"\d+" 匹配一个数字 (\d) 一次或多次。
这 ”\。?” 是小数点(用“\”转义以消除它的魔力),零次或一次。
The last part "\d*" is again a digit, zero or more times.
All the parts are optional but the first digit, so this group matches numbers like 5. and not .5 which are matched by the other half.
最后一部分 "\d*" 再次是一个数字,零次或多次。
除了第一个数字之外,所有部分都是可选的,因此该组匹配 5. 之类的数字,而不是与另一半匹配的 0.5。
回答by Muhammad Adeel
\dwill not match the decimal point. Use the following for the decimal.
\d将不匹配小数点。使用以下小数点。
const re = /^\d*(\.\d+)?$/
'123'.match(re) // true
'123.3'.match(re) // true
'123!3'.match(re) // false
回答by leonardo rey
Why dont use something like:
为什么不使用类似的东西:
$.isNumeric($(input).val())
Is jquery tested, and the most common case are checked
是jquery测试的,最常见的情况都检查了
回答by Andrej
If you need just positive integer numbers and don't need leading zeros (e.g. "0001234" or "00"):
如果您只需要正整数而不需要前导零(例如“0001234”或“00”):
var reg = /^(?:[1-9]\d*|\d)$/;