繁体   English   中英

正则表达式 - 验证逗号分隔的数字列表,长度为 1 到 3 位

[英]Regex - validating comma-separated list of numbers, 1 to 3 digits long

我正在尝试验证以逗号分隔的数字列表,其中数字可以是 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 在这里也无效,但应该有效

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

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

正则表达式演示

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

在这种情况下

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

  • 每组允许一到三个号码
  • 允许一对多组
  • 不允许 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. // ie '^((?!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(''));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM