Reputation: 59234
Examples that should match the regex:
I want to create a regular expression that matches a comma-delimited list with these rules:
What I have so far (doesn't work):
/^([a-z0-9]{2,30}, ?)?[a-z0-9]{2, 30}$/i
Upvotes: 2
Views: 111
Reputation: 213401
Try out this:
/^[a-z0-9-]{2,30}(,\s?[a-z0-9-]{2,30}){0,4}$/i
Break up:
/^
[a-z0-9-]{2,30} # One item for sure
( # A capture group. You can make it non-capture if not required
,\s? # Comma followed by optional space
[a-z0-9-]{2,30} # Another item
){0,4} # 0 to 4 repetition.
$/ix
You can even shorten your regex by using \w
, which is equivalent to - [0-9a-zA-Z_]
, after your updated comment, where you said you can accept _
also. So, just use this:
/^[\w-]{2,30}(, ?[\w-]{2,30}){0,4}$/
Upvotes: 8
Reputation: 149078
Something like this should work:
/^([a-z0-9-]{2,30}, ?){0,4}[a-z0-9-]{2,30}$/i
This will match a 2 to 30 Latin letters or decimal digits or hyphens, followed by a comma and an optional space, all repeated 0 to 4 times, followed by 2 to 30 Latin letters or decimal digits or hyphens.
You can test it out here.
Upvotes: 4
Reputation: 191819
/^[^,]{2,30}(, ?[^,]{2,30}){0,4}$/
The [^,]
are used because you didn't specify allowed characters so I assume that only comma is not allowed. You could of course use [a-zA-Z0-9_-]
, \w
, or any other restrictions on that character class.
Upvotes: 1