![](/img/trans.png)
[英]Regular expression in javascript to not allow only whitespaces in a field but allow string with whitespaces and also allow empty field
[英]Javascript Regular Expression - Filter only integer string also negative
我正在尝试创建一个字符串的正则表达式验证,我想检查string是整数字符串,是正数还是负数。
我尝试创建表达式,但只能过滤带有符号“-”的数字,但是我无法将其以“-”开头(可选)并在末尾包含任何数字的真实字符串进行匹配。
这是我的尝试:
var intRegex = /^[-?\d]+$/g;
console.log(intRegex.test('55')); // true
console.log(intRegex.test('artgz')); // false
console.log(intRegex.test('55.3')); // false
console.log(intRegex.test('-55')); // true
console.log(intRegex.test('--55')); // true but I don't want this true
console.log(intRegex.test('5-5')); // true but I don't want this true
任何想法?
您可以使用/^-?\\d+$/
,您只希望连字符(-)0或1次,所以您使用? 在-之后,并且\\ d可以是1次或多次,因此只能将+用于\\ d。
var intRegex = /^[-]?\\d+$/g; console.log(intRegex.test('55')); // true console.log(intRegex.test('artgz')); // false console.log(intRegex.test('55.3')); // false console.log(intRegex.test('-55')); // true console.log(intRegex.test('--55')); // true but I don't want this true console.log(intRegex.test('5-5')); // true but I don't want this true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.