简体   繁体   中英

comma and space separated number and hyphen separated string regular expression

I have to validate the following string using jquery i need regex please help find solution for this,

The valid strings are,

(1)1,2,3,4,1,2-8
(2)1,2, 3, 4, 1, 2-8

Should also accept commas and commas with spaces and also the number should be hyphen separated

I have tried the following regex ,

^([0-9]+(-[0-9]+)?)(,([0-9]+(-[0-9]+)?))*$

This one works for the strings you posted:

var rx = new RegExp(/^\(\d\)(\d,\s*){5}\d\-\d$/);

However, it wasn't clear to me whether the (1) and (2) were supposed to be part of the strings. If not, use this:

var r2 = new RegExp(/^(\d,\s*){5}\d\-\d$/);
// a digit, followed by a comma, followed by some whitespace, repeated five times
// with a digit-hyphen-digit sequence at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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