[英]Javascript Regular Expression - Filter only integer string also negative
I'm trying to create a regex validation of a string and I want to check if string is an integer string, positive or negative. 我正在尝试创建一个字符串的正则表达式验证,我想检查string是整数字符串,是正数还是负数。
I tryed to create my expression and I'm able to filter only digit with symbol '-' but I can't match as true string that begin with '-' (optional) and contains any digit at the end. 我尝试创建表达式,但只能过滤带有符号“-”的数字,但是我无法将其以“-”开头(可选)并在末尾包含任何数字的真实字符串进行匹配。
This is my try: 这是我的尝试:
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
Any idea? 任何想法?
you can use /^-?\\d+$/
, you want hyphen(-) only 0 or 1 times, so you use ? 您可以使用
/^-?\\d+$/
,您只希望连字符(-)0或1次,所以您使用? after -, and \\d can be 1 or more times so use + for \\d only. 在-之后,并且\\ 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.