Hitrene :
I want to create regex, that will match second names with whitespaces and dashes, like:
Smith-Wright
Smith
Smith Wright
But if you will enter just - or whitespace, it shouldn't work. For now I have a regex like ^[a-zA-Z\s\-]+$
, but it watches words with only - and whitespaces. How to create regex that will match words with only my separators?
Pushpesh Kumar Rajwanshi :
You can use this regex for the kind of names you want to match,
^[a-zA-Z]+(?:[ -][a-zA-Z]+)*$
Explanation:
^
- Start of string[a-zA-Z]+
- Match a name consisting of alphabets one or more characters(?:[ -][a-zA-Z]+)*
- Additionally match more name part provided it is space or hyphen separated.$
- End of string