简体   繁体   English

使用正则表达式验证逗号分隔的数字字符串?

[英]Validate comma separated string of numbers with Regular Expression?

I need a regular expression for validation of 3 numbers then , and again 3 numbers and again basically any number of times.我需要3个数字的验证正则表达式,然后,又一次3号又一次基本上任意次数。 And comma can be at the begining or it can be at the end (but strictly one).逗号可以在开头,也可以在结尾(但严格来说是一个)。

So, these are valid inputs:所以,这些是有效的输入:

,111,111, ,111,111,

112,112, 112,112,

,112,112,113,114,111, ,112,112,113,114,111,

,114,115 ,114,115

,142, ,142,

,141 ,141

Invalid inputs:无效输入:

,, ,,

, , , ,

,,145,,, ,,145,,,

I have made like:我做了这样的:

var re = /^[0-9]{3}([,][0-9]{3})*$/;

But it is not working well and it is only accepting 2 groups.但它运行得不好,它只接受 2 个组。 And always want comma at the end.并且总是在末尾想要逗号。

You may use this regex:您可以使用此正则表达式:

^,?(?:\d{3},)*\d{3},?$

RegEx Demo正则表达式演示

Replace \\d with [0-9] if it is not supported in your regex platform.如果您的正则表达式平台不支持\\d ,请将其替换为[0-9]

RegRx Description: RegRx 说明:

  • ^,? : Match an optional , at the start : 匹配一个可选的,在开始
  • (?:\\d{3},)* : Match a non-capturing group 0 or more times. (?:\\d{3},)* :匹配一个非捕获组 0 次或更多次。 We match a 3 digit number followed by , inside this group.我们匹配一个 3 位数字后跟,在这个组内。
  • \\d{3} : Match a 3 digit number \\d{3} : 匹配一个 3 位数字
  • ,?$ : Match an optional , at the end ,?$ : 匹配一个可选的,最后

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

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