【问题标题】:Regex - validating comma-separated list of numbers, 1 to 3 digits long正则表达式 - 验证逗号分隔的数字列表,长度为 1 到 3 位
【发布时间】:2020-01-09 15:11:06
【问题描述】:

我正在尝试验证以逗号分隔的数字列表,其中数字可以是 1 到 3 位数字,可以以 0 开头但不能为 0(0、00 或 000)。我在下面使用,但是当我测试“44,222,555”时我变得无效:

^([1-9]|[0-9][1-9]|[0-9][0-9][1-9](?:,(?:[1-9]|[0-9][1-9]|[0-9][0-9][1-9]))*)$

我认为 90 在这里也是无效的,但应该是有效的

【问题讨论】:

  • 可以是003吗?只是不是 0,00,000。对吗?
  • 例如:1,22,333,010,001,100,999。这样可以吗?

标签: javascript regex


【解决方案1】:

您可以使用负前瞻来简化您的正则表达式:

/^(?!0+\b)[0-9]{1,3}(?:,(?!0+\b)[0-9]{1,3})*$/gm

RegEx Demo

(?!0+\b) 是负前瞻,如果我们在当前位置之前的字边界前有一个或多个零,则匹配失败。

【讨论】:

    【解决方案2】:

    在这种情况下

    注意:根据字符串的大小,不使用全局标志会提高速度。

    • 每组允许一到三个数字
    • 允许一对多集
    • 0、00、000 不允许基于零的组合
    • 允许 01、010、001、100 个基于零的组合
    • 如果多于一组数字,则组之间用逗号分隔
    • 不允许以逗号结尾

    let regex = new RegExp('^((?!0+\\b)[0-9]{1,3}\,?\\b)+$');
    
    // NOTE: If using literal notation /regex/.test() then "\" is not escaped.
    // i.e. '^((?!0+\\b)[0-9]{1,3}\,?\\b)+$' becomes /^((?!0+\b)[0-9]{1,3}\,?\b)+$/
    // /^((?!0+\b)[0-9]{1,3}\,?\b)+$/.test(string);
    
    console.log('Passes question test: 44,222,555 ', regex.test('44,222,555'));
    console.log('Passes question test: 90 ', regex.test('90'));
    console.log('Can contain multiple sets of one to three numbers: ', regex.test('1,22,333'));
    console.log('Cannot have more than three numbers in a set 1234', !regex.test('1234'));
    console.log('Can have one number in a set ', regex.test('1'));
    
    console.log('Cannot have 0 alone as a set: ', !regex.test('0'));
    console.log('Cannot have 00 alone as a set: ', !regex.test('00'));
    console.log('Cannot have 000 alone as a set: ', !regex.test('000'));
    
    console.log('Cannot end in a comma ', !regex.test('123,'));
    
    console.log('Cannot contain multiple commas next to each other ', !regex.test('123,,694'));
    console.log('Allowed zero combinations are 00#, #00, 0#0, 00#, ##0, 0## ', regex.test('001,100,010,001,110,011'));
    console.log('Cannot be just a comma ', !regex.test(','));
    console.log('Cannot be a blank string ', !regex.test(''));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      相关资源
      最近更新 更多