【问题标题】:Javascript Regular Expression - Filter only integer string also negativeJavascript正则表达式 - 仅过滤整数字符串也是负数
【发布时间】:2017-10-07 15:17:13
【问题描述】:

我正在尝试创建字符串的正则表达式验证,并且我想检查字符串是整数字符串,正数还是负数。

我尝试创建我的表达式,我只能过滤带有符号“-”的数字,但我无法匹配以“-”(可选)开头且末尾包含任何数字的真实字符串。

这是我的尝试:

    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

有什么想法吗?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    你可以使用/^-?\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

    【讨论】:

    • [-] 最好写成-
    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多