max max - 23 days ago 5
HTML Question

Pattern for input to allow multiple hashtags, divided by whitespace (#one #two)

Please help me to define a pattern for pattern attribute of input element (

<input pattern="myPattern">
) which allows to type one or more hashtags, divided by space.
For example:

#first //valid
#Second #and-3rd //valid
#one#two //invalid


I tried
(^|\s)(#[a-z\d-]+)
, but it works only for one tag in input. How can I enhance it to allow multiple tags?

Thanks in advance.

Answer

You can use this regex to allow for words starting with # and separated by space:

^#[\w-]+(?:\s+#[\w-]+)*$

RegEx Demo

RegEx Description:

^           # Start
#           # match literal #
[\w-]+      # match 1 or more word chars or hyphen
(?:         # start non-capturing group
   \s+      # match 1 or more whitespace
   #        # match literal #
   [\w-]+   # match 1 or more word chars or hyphen
)*          # end of capturing group. * makes this group match 0 more times
$           # End

PS: Note that anchors ^ and $ are not needed when reges is used in input pattern.

Comments