user2211311
user2211311

Reputation: 73

I allow only one hyphen (-) in regex

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]*$

Upvotes: 3

Views: 13704

Answers (5)

Sergiu Toarca
Sergiu Toarca

Reputation: 2749

I am assuming you want up to 1 hyphen. If so, the regex you want is

^[a-z A-Z]*-?[a-z A-Z]*$

You can visualize it on www.debuggex.com.

Upvotes: 2

Marcin Pietraszek
Marcin Pietraszek

Reputation: 3214

Your regular expression allow exactly one -. but I assume that you want to mach "Smith", "Smith-Kennedy", but not "Smith-", to do this you just must move the hyphen to the second group:

^[a-z A-Z]+(-[a-z A-Z]+)?$

BTW, in almost all cases when * is used + is the better solution.

Upvotes: 3

fardjad
fardjad

Reputation: 20394

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.

Upvotes: 3

Denys Séguret
Denys Séguret

Reputation: 382150

A problem with your regex is that it forces the user to put a -. You can use ? to make it optional :

^[a-z A-Z]*\-?[a-zA-Z]*$

Upvotes: 1

Roman Saveljev
Roman Saveljev

Reputation: 2594

If it matches .*-.*-, then you have more than one hyphen and such string should not be accepted

Upvotes: 0

Related Questions