[英]How can I craft a regular expression to match a comma delimited list with a maximum of 5 items in the list?
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
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. 您甚至可以使用\\w
缩短正则表达式,这相当于 - [0-9a-zA-Z_]
,在更新后的评论之后,您说您也可以接受_
。 So, just use this: 所以,只需使用:
/^[\w-]{2,30}(, ?[\w-]{2,30}){0,4}$/
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. 这将匹配2到30个拉丁字母或十进制数字或连字符,后跟逗号和可选空格,全部重复0到4次,然后是2到30个拉丁字母或十进制数字或连字符。
/^[^,]{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. 您当然可以使用[a-zA-Z0-9_-]
, \\w
或该角色类的任何其他限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.