我想在任何地方只允许数字和短划线。 请有人分享您的想法! 我尝试了一些,但对我不起作用...... / ^ [0-9 - ] + $ / \ d + [ - ] + \ d \,[0-9] +
答案 0 :(得分:1)
如果我没弄错,你试过多个正则表达式。
此^[0-9-]+$
将匹配数字和短划线,但也会匹配---5555
,因为您将它们添加到字符集中并重复它们。
此\d+[-]+\d
会匹配一个或多个数字,一个破折号,然后是一个数字。
此[0-9]+
仅匹配数字。
只允许使用数字和短划线:
这将匹配
^ # From the beginning of the string \d+ # match one or more digits (?: # A non capturing group -\d+ # Match a dash and one or more digits )* # Close non capturing group and repeat zero or more times $ # The end of the string
要仅允许使用短划线的单个数字,您可以使用^\d(?:-\d)*$
。
这些与开头或结尾处的短划线不匹配,仅在数字之间。
若要至少有1个短划线,则使用+
而不是*
重复非捕捉组一次或多次,这将匹配零次或多次。