Java regex word bounderies

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

Regex Demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77573&siteId=1