【问题标题】:Regular Expression for any number excluding specific numbers任何数字的正则表达式,不包括特定数字
【发布时间】:2016-01-05 12:59:32
【问题描述】:

我想制作一个正则表达式来捕获每个整数(正数和负数),只要它不是以下之一:-2、-1、0、1、2 或 10。

所以这些应该匹配:-11、8、-4、11、15、121、3 等。

到目前为止,我有这个正则表达式:/-?([^0|1|2|10])+/

它捕获负号,但是当数字为 -2 或 -1 时它仍然会捕获负号,这是我不想要的。此外,它不会捕获 11。

我应该如何更改表达式以匹配我想要查找的数字。另外,有没有更好的方法在字符串中查找这些数字?

【问题讨论】:

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


    【解决方案1】:

    我应该如何更改表达式以匹配我想要查找的数字。另外,有没有更好的方法在字符串中查找这些数字?

    只需使用简单的正则表达式来匹配字符串中的所有数字,然后过滤数字

    // Define the exclude numbers list:
    // (for maintainability in the future, should excluded numbers ever change, 
    // this is the only line to update)
    var excludedNos = ['-2', '-1', '0', '1', '2', '10'];
    
    var nos = (str.match(/-?\d+/g) || []).filter(function(no) {
        return excludedNos.indexOf(no) === -1;
    });
    

    Demo

    【讨论】:

    • var str = '-2, -1, 0, 1, 2, or 10 -11, 8, -4, 11, 15, 121, 3';我得到 nos = [“2”、“1”、“0”、“1”、“2”、“10”、“11”、“8”、“4”、“11”、“15”、“ 121", "3"]
    • @RichS 检查Demo,那是因为excludedNos 数组包含数字,match 返回数组中的字符串,正在更新
    • 这段代码似乎是解决所提问题的最简单、最优雅的方式。
    • @RichS 很高兴听到这个消息!
    • 建议编辑。如果您不喜欢,请随意拒绝。基本上编辑到正确答案的部分。
    【解决方案2】:
    -?(?!(?:-?[012]\b)|10\b)\d+\b
    

    只需添加一个lookahead 删除您不想要的号码。查看演示。

    https://regex101.com/r/cJ6zQ3/33

    var re = /-?(?!(?:-?[012]\b)|10\b)\d+\b/gm; 
    var str = '-2, -1, 0, 1, 2, or 10 -11, 8, -4, 11, 15, 121, 3';
    var m;
    
    while ((m = re.exec(str)) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        // View your result using the m-variable.
        // eg m[0] etc.
    }
    

    【讨论】:

    • 测试字符串:var a = "-11, 8, -4, 11, 15, 121, 3, abacoijaoiefjp -2 -1 0 ajoiefjaio 0 1 2 10" a.match(/-? (?!(?:-?[012]\b)|10\b)\d+\b/) 返回 ["-11"]
    【解决方案3】:

    您可以使用-?(?!([012]|10)\b)\d+\b 否定前瞻断言将解决您的问题

    var res = ' -2, -1, 0, 1, 2, or 10 11, 8, -4, 11, 15, 121, 3,'.match(/-?(?!([012]|10)\b)\d+\b/g);
    console.log(res);

    Regex explanation here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      相关资源
      最近更新 更多