以逗号分隔的 REGEX 唯一编号 [英] REGEX unique numbers delimited by comma

查看:29
本文介绍了以逗号分隔的 REGEX 唯一编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证逗号分隔的数字 1-31 唯一列表(不重复).

I am trying to validate a comma separated list of numbers 1-31 unique (not repeating).

  • 2,4,6,7,1 是有效输入.

  • 2,4,6,7,1 is valid input.

2,2,6 无效

2 有效

2,无效

1,2,3,4,15,6,7,31 有效

1,2,3,4,15,6,7,31 is valid

1,2,3,4,15,6,7,32 无效

1,2,3,4,15,6,7,32 is invalid

20,15,3

我试过了<代码>^((([0]?[1-9])|([1-2][0-9])|(3[01]))(?!([0]?[1-9]])|([1-2][0-9])|(3[01])*,\\1(?!([0]?[1-9])|([1-2][0]-9])|(3[01])) 但它接受重复的数字

I tried ^((([0]?[1-9])|([1-2][0-9])|(3[01]))(?!([0]?[1-9])|([1-2][0-9])|(3[01])*,\\1(?!([0]?[1-9])|([1-2][0-9])|(3[01])) but it's accepting repeating numbers

推荐答案

对于超过 1 位数的数字范围,只需在周围添加单词边界
捕获组和反向引用.
隔离一个完整的数字.

For a number range that exceeds 1 digit, just add word boundary's around
the capture group and the back reference.
This isolates a complete number.

这个特殊的范围是 1-31

This particular one is numb range 1-31

 ^                                       # BOS
 (?!                                     # Validate no dups
      .* 
      (                                       # (1 start)
           \b 
           (?: [1-9] | [1-2] \d | 3 [0-1] )        # number range 1-31
           \b 
      )                                       # (1 end)
      .* 
      \b \1 \b 
 )
 (?: [1-9] | [1-2] \d | 3 [0-1] )        # Unrolled-loop, match 1 to many numb's
 (?:                                     # in the number range 1-31
      , 
      (?: [1-9] | [1-2] \d | 3 [0-1] )
 )*
 $                                       # EOS

    var data = [
      '2,4,6,7,1',
      '2,2,6',
      '2,30,16,3',
      '2,',
      '1,2,3,2',
      '1,2,2,3',
      '1,2,3,4,5,6,7,8'
      ];
      
      data.forEach(function(str) {
        document.write(str + ' gives ' + /^(?!.*(\b(?:[1-9]|[1-2]\d|3[0-1])\b).*\b\1\b)(?:[1-9]|[1-2]\d|3[0-1])(?:,(?:[1-9]|[1-2]\d|3[0-1]))*$/.test(str) + '<br/>');
      });

这篇关于以逗号分隔的 REGEX 唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆