Regex to match '-' delimited alphanumeric words

前端 未结 4 1162
独厮守ぢ
独厮守ぢ 2020-12-19 18:21

I would like to test if user type only alphanumeric value or one \"-\".

hello-world                 -> Match
hello-first-world           -> match
this-         


        
4条回答
  •  無奈伤痛
    2020-12-19 19:01

    I'm not entirely sure if this works because I haven't done regex in awhile, but it sounds like you need the following:

    /^[A-Za-z0-9]+(-[A-Za-z0-9]+)+$/

    You're requirement is split up in the following:

    • One or more alphanumeric characters to start (that way you ALWAYS have an alphanumeric starting.
    • The second half entails a "-" followed by one or more alphanumeric characters (but this is optional, so the entire thing is required 0 or more times). That way you'll have 0 or more instances of the dash followed by 1+ alphanumeric.

    I'm just not sure if I did the regex properly to follow that format.

提交回复
热议问题