Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end

前端 未结 4 714
故里飘歌
故里飘歌 2021-02-14 12:15

Update:

This question was an epic failure, but here\'s the working solution. It\'s based on Gumbo\'s answer (Gumbo\'s was close to working so I chose it as the accepte

4条回答
  •  渐次进展
    2021-02-14 13:14

    Try this regular expression:

    ^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
    

    This regular expression does only allow hyphens to separate sequences of one or more characters of [a-zA-Z0-9].


    Edit    Following up your comment: The expression (…)* allows the part inside the group to be repeated zero or more times. That means

    a(bc)*
    

    is the same as

    a|abc|abcbc|abcbcbc|abcbcbcbc|…
    

    Edit    Now that you changed the requirements: As you probably don’t want to restrict each hyphen separated part of the words in its length, you will need a look-ahead assertion to take the length into account:

    (?=[a-zA-Z0-9-]{4,25}$)^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
    

提交回复
热议问题