I allow only one hyphen (-) in regex

后端 未结 5 464
猫巷女王i
猫巷女王i 2020-12-18 17:27

I have a text box where i get the last name of user. How do I allow only one hyphen (-) in a regular expression?

^([a-z A-Z]*-){1}[a-z A-Z]*$
5条回答
  •  眼角桃花
    2020-12-18 17:51

    you can use negative lookahead to reject strings having more than one hyphen:

    ^(?![^-]+-[^-]+-)[a-zA-Z- ]+$
    

    Matched demo on debuggex.

    Another Matched demo on debuggex.

    Not Matched Demo demo on debuggex.

提交回复
热议问题