Regex to match '-' delimited alphanumeric words

前端 未结 4 1137
独厮守ぢ
独厮守ぢ 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.

    0 讨论(0)
  • 2020-12-19 19:02

    (^-)|-{2,}|[^a-zA-Z-]|(-$) looks for invalid characters, so zero matches to that pattern would satisfy your requirement.

    0 讨论(0)
  • 2020-12-19 19:07

    Here you go (this works).

    var regExp = /^[A-Za-z0-9]+([-]{1}[A-Za-z0-9]+)+$/;
    

    letters and numbers greedy, single dash, repeat this combination, end with letters and numbers.

    0 讨论(0)
  • 2020-12-19 19:13

    Try this:

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

    This will only match sequences of one or more sequences of alphanumeric characters separated by a single -. If you do not want to allow single words (e.g. just hello), replace the * multiplier with + to allow only one or more repetitions of the last group.

    0 讨论(0)
提交回复
热议问题