HTML5 Pattern for allowing only 5 comma separated words without including a space

核能气质少年 提交于 2021-01-28 10:45:05

问题


I basically don't know how to make HTML5 Patterns so that's why I am asking this question. I just want to create a pattern that would be applied onto a input[type=text] thorough pattern attribute newly introduced by the HTML5 but I have no idea on how to implement that pattern.

The pattern includes the following things:

  1. Allow only 5 comma separated words
  2. No space could be added.

回答1:


^(\w+,){4}\w+$ is the pattern you need: repeat "any number of word characters followed by comma" four times, then "just word characters". If you want "up to five", the solution would be

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

Detailed explanation (adapted from 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

If you don't want numbers as part of the match, replace every instance of \w in the above with [a-zA-Z] - it will match only lowercase and uppercase letters A through Z.

UPDATE In response to your comment, if you want no group of characters to be more than 10 long, you can modify the above expression to

^(\w{1,10},){0,4}\w{1,10}$

Now the "quantifier" is {1,10} instead of + : that means "between 1 and 10 times" instead of "1 or more times".



来源:https://stackoverflow.com/questions/20846919/html5-pattern-for-allowing-only-5-comma-separated-words-without-including-a-spac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!