【问题标题】:RegEx for testing plus or minus sings in numbers [duplicate]用于测试正负数的正则表达式 [重复]
【发布时间】:2019-05-23 18:23:35
【问题描述】:

我正在尝试使用regex.test 来查看数字的开头是否有“+”或“-”。什么是最好的解决方案? 我试过这个:

var regex = RegExp('^[0-9]*$');
var str1 = +384572985;
console.log(regex.test(str1)); //return true

var str2 = "+384572985";
console.log(regex.test(str2)); //return false

但我希望它们都返回 false!

【问题讨论】:

    标签: javascript regex regex-negation regex-lookarounds regex-group


    【解决方案1】:

    str1 不是字符串。它被转换成一个字符串。由于操作顺序,+123 在评估正则表达式之前仅评估为 123。这就像运行/3/.test(1+2)

    【讨论】:

      【解决方案2】:

      我不确定什么是最好的方法,但是我们可以使用类似于以下的表达式来做到这一点:

      ^[+-][0-9]+$
      

      测试

      const regex = /^[+-][0-9]+$/gm;
      const str = `+384572985
      -384572985
      ++384572985
      384572985`;
      let m;
      
      while ((m = regex.exec(str)) !== null) {
          // This is necessary to avoid infinite loops with zero-width matches
          if (m.index === regex.lastIndex) {
              regex.lastIndex++;
          }
          
          // The result can be accessed through the `m`-variable.
          m.forEach((match, groupIndex) => {
              console.log(`Found match, group ${groupIndex}: ${match}`);
          });
      }

      正则表达式

      如果不需要此表达式,可以在 regex101.com 中修改或更改它。

      正则表达式电路

      jex.im 可视化正则表达式:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        相关资源
        最近更新 更多