HTML5模式,仅允许5个逗号分隔的单词而不包含空格

时间:2013-12-30 20:23:30

标签: javascript regex html5

我基本上不知道如何制作HTML5模式,这就是我问这个问题的原因。我只是想创建一个模式,该模式将应用于HTML5新引入的input[type=text]彻底pattern属性,但我不知道如何实现该模式。

该模式包括以下内容:

  1. 仅允许5个逗号分隔的单词
  2. 无法添加空间。

1 个答案:

答案 0 :(得分:5)

^(\w+,){4}\w+$是您需要的模式:重复“任意数量的单词字符后跟逗号”四次,然后“只需单词字符”。如果您想要“最多五个”,解决方案将是

^(\w+,){0,4}\w+$

详细解释(改编自http://www.regex101.com):

^      assert position at start of the string (i.e. start matching from start of string)

1st    Capturing group (\w+,){0,4}
   Quantifier {0,4}: Between 0 and 4 times, as many times as possible, giving back as needed [greedy]

\w+    match any word character [a-zA-Z0-9_]
   Quantifier +: Between one and unlimited times, as many times as possible, giving back as needed [greedy]

,      matches the character , literally

\w+    match any word character [a-zA-Z0-9_]
   Quantifier +: Between one and unlimited times, as many times as possible, giving back as needed [greedy]

$ assert position at end of the string

如果您不希望数字作为匹配的一部分,请将\w中的[a-zA-Z]的每个实例替换为^(\w{1,10},){0,4}\w{1,10}$ - 它将只匹配小写和大写字母A到Z.

更新在回复您的评论时,如果您不希望任何字符组长度超过10条,则可以将上述表达式修改为

{1,10}

现在“量词”是+而不是{{1}}:这意味着“介于1到10次之间”而不是“1次或更多次”。