Regex to allow single hyphen and underscore but not at beginning or end of string

前端 未结 2 690
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-20 15:51

I have this Regex I modified to allow underscores, hyphen, letters and numbers. I am trying to modify it further so that it has the following properties:

  1. Allow
相关标签:
2条回答
  • 2021-01-20 16:07

    Try this:

    ^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$
    

    Or this, which will simply ensure that the string does not start with a hyphen or underscore:

    ^[a-zA-Z0-9][a-zA-Z0-9_-]*$
    
    0 讨论(0)
  • 2021-01-20 16:07
    ^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9])$
    

    Either one of the three possibilities:

    • [a-zA-Z0-9]
    • [a-zA-Z0-9][a-zA-Z0-9]
    • [a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]
    0 讨论(0)
提交回复
热议问题