4

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?

2 Answers 2

3

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

Regex Demo

Sign up to request clarification or add additional context in comments.

2 Comments

But it's not matches just "Smith". What I should add to match this?
If you just want to match Smith just change last + to * Demo which will make the later part zero or more and hence optional
1

If I understand your post correctly, you want to match:

  • "Smith-Wright"
  • "Smith"
  • "Smith Wright"

but not

  • "-"
  • " "
  • "-Wright"
  • " Wright"

If that's correct, you can use:

^[a-zA-Z]+([ -][a-zA-Z]+)*$

You can put your separators in place of [ -].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.