简体   繁体   English

如何制作正则表达式以匹配逗号分隔列表,列表中最多包含5个项目?

[英]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: 应该与正则表达式匹配的示例:

  • green, yellow-3, 12345, hello, world 绿色,黄色3,12345,你好,世界
  • blue, red, teal, orange 蓝色,红色,蓝绿色,橙色
  • green,12345, world 绿色,12345,世界
  • hello, there 你好
  • green 绿色

I want to create a regular expression that matches a comma-delimited list with these rules: 我想创建一个与逗号分隔的列表匹配的正则表达式:

  • The list can contain 1, 2, 3, 4, or 5 items. 该列表可以包含1个,2个,3个,4个或5个项目。
  • The items must not contain white space except for an optional space after each comma. 除了每个逗号后面的可选空格外,这些项目不得包含空格。
  • The last item must not have a trailing comma. 最后一项不能有逗号。
  • Each item must be between 2 and 30 characters. 每个项目必须介于2到30个字符之间。

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个拉丁字母或十进制数字或连字符。

You can test it out here . 你可以在这里测试一下

/^[^,]{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.

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