简体   繁体   English

验证逗号分隔的数字

[英]Validate comma separated numbers

I have to check if a string has this pattern: 1,2,10,11 . 我必须检查字符串是否具有以下模式: 1,2,10,11

The rules are: 规则是:

  • It may be a sequence like: 1 or 1,2 or 1,2,n+1 . 它可以是类似11,21,2,n+1的序列。 Many numbers user wants; 用户想要的数字很多;
  • The number must be followed by a comma but can't ends with it, like: 1, ; 该数字后面必须带有逗号,但不能以逗号结尾,例如: 1, ;;
  • The number can have 1 or 2 digits; 该数字可以是1或2位数字;
  • No other character but number and comma, no space or whatever; 除了数字和逗号,没有其他字符,没有空格或其他字符;
  • No need to check numbers sequence, this is not the point. 无需检查数字顺序,这不是重点。

What I have tried is: 我试过的是:

  • (\\d{1,2})(,) : This code checks for a 1, sentence and returns true no metters what is on the rest of the string, like 1,afasfs ; (\\d{1,2})(,) :此代码检查一个1,句子,不返回true不返回字符串其余部分的内容,例如1,afasfs
  • I've tried look ahead: (\\d{1,2})(?=(,)) but it accepts the above case too; 我已经试过了: (\\d{1,2})(?=(,))但它也接受上述情况;
  • The both cases above I can't apply ^ and $ because it fails on right scenarios like: 1,2,3 . 上面的两种情况我都不能应用^$因为它在诸如1,2,3正确情况下失败。

What I don't know is how to test the entire string. 我不知道如何测试整个字符串。 All my tests only checks a part of it(eg 1, ) not the entire string. 我所有的测试仅检查其中一部分(例如1, ),而不检查整个字符串。

Note: I'm using JavaScript test() function. 注意:我正在使用JavaScript test()函数。 Don't know if is the right one, but I believe that it is. 不知道是否正确,但我相信是正确的。

You can try this regex: 您可以尝试以下正则表达式:

/^(\d{1,2},)*\d{1,2}$/

Details: 细节:

^           - Line start
\d{1,2}     - 1 or 2 digit number
\d{1,2},    - 1 or 2 digit number followed by a comma
(\d{1,2},)* - 0 or more of 1/2 digit number followed by a comma character
\d{1,2}     - 1 or 2 digit number
$           - Line end

正则表达式可视化

per OP 每个OP

The number must be followed by a comma 该数字后必须带有逗号

so a little modification to anubhava's pattern /^(\\d{1,2},)+\\d{1,2}$/ otherwise it will validate single or double digits only like 1 or 10 因此,对aubhava的模式/^(\\d{1,2},)+\\d{1,2}$/进行一些修改,否则它将只验证110一位或两位数

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

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