我正在尝试创建一个字符串的regex验证,我想检查字符串是整数字符串,正字符串还是负字符串。
我尝试创建我的表达式,我只能过滤符号'-‘的数字,但我不能匹配真正的字符串,以'-’(可选),并包含任何数字在结尾。
这是我的尝试:
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
有什么想法吗?
发布于 2017-10-07 15:24:05
您可以使用/^-?\d+$/
,您希望连字符(-)只使用0或1次,所以您使用?在-之后,和\d可以是1次或更多次,所以只使用+ for \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
https://stackoverflow.com/questions/46621799
复制相似问题