简体   繁体   English

Javascript正则表达式-仅过滤整数字符串,也为负数

[英]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.

相关问题 JavaScript中的正则表达式不仅不允许字段中包含空格,而且允许包含空格的字符串,还允许包含空字段 - Regular expression in javascript to not allow only whitespaces in a field but allow string with whitespaces and also allow empty field 使用php和javascript匹配字符串中最后一个整数的正则表达式 - Regular expression to match the last integer in a string with php and javascript JavaScript正则表达式(当且仅当) - JavaScript Regular Expression (If and only if) 如何编写 javascript 正则表达式,它接受数字范围在 8 到 15 integer 之间的十进制数? - how to write javascript regular expression that accept number range between 8 to 15 integer with decimal number also? 使用 JavaScript 中的正则表达式过滤字符串中的逗号和空格 - Filter Comma and Whitespace in String using Regular Expression in JavaScript 使用javascript中的正则表达式从字符串中滤除百分比 - filter out a percentage from a string using a regular expression in javascript 正则表达式,JavaScript背后的负面印象 - Regular Expression, negative look behind javascript 带有小数的负数的Javascript正则表达式 - Javascript regular expression for negative Numbers with decimal 正则表达式 - 也允许空字符串 - Regular expression - also empty string allowed 正则表达式仅匹配javascript中字符串的时间值 - Regular expression to match only time value from string in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM