输入模式允许多个标签,用空格分隔(#one #two)

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

本文关键字:分隔 #one #two 空格 许多个 标签 输入模式      更新时间:2023-09-26

请帮我定义输入元素(<input pattern="myPattern">)的模式属性的模式,该模式允许输入一个或多个标签,按空格划分。例如:

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

我尝试了(^|'s)(#[a-z'd-]+),但它只适用于输入中的一个标签。我如何增强它以允许多个标签?

您可以使用此正则表达式允许以#开头并以空格分隔的单词:

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

RegEx演示

正则表达式描述:

^           # 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:注意,input模式使用reges时,不需要^$锚。