user1312164
user1312164

Reputation: 71

Regular expression to match single first name string or first and last name string with one space and one hyphen

Regular expression to match single first name string or first and last name string with one space and one hyphen.

Valid matches

  1. Mathias d-arras
  2. Martin Luther
  3. Hector-Sausage
  4. Mathias
  5. John-Paul Mathias
  6. Jhon S
  7. K Jhon
  8. k jhon-m
  9. J-m k
  10. k j-m

Invalid matches

  1. Mathias d arras
  2. Mathias- darras
  3. Hector -Sausage
  4. Hector Sau K
  5. Hector-Sau-K
  6. Hector Sausage-
  7. a-a aa-a
  8. a-a aa a
  9. Jean-Paul Simmons-Beckett
  10. a-a a-a
  11. a a a

Upvotes: 0

Views: 123

Answers (3)

talemyn
talemyn

Reputation: 7950

This pattern will correctly match the sample data that you provided (I'm assuming that you actually only want to allow spaces [], not all whitespaces [\s], which would also include tabs, line breaks, etc):

/^[a-z]+( [a-z][a-z-]+||-[a-z]+)?$/i

Though, I wonder if there aren't some other situations that you've missed in your sample data, such as:

  • John-Paul Mathias (valid, but would fail?)
  • Hector Sausage- (invalid, but would pass?)

There would need to be some more tweaks to handle those, if they are needed.

Also, I left out the g and m flags, since this looks like a pattern validation, in which case, I wouldn't think you would need them. If you actually need to capture multiple instances of this pattern in a multi-line situation, then, you would need those flags put back in.

UPDATE

Okay, based on those other pieces of test data, the following regex will work:

/^[a-z]+-?[a-z]+( [a-z]+-?[a-z]+)?$/i

I keep feeling like there is a way to trim it down even more, but the complex relationship between the and - characters are making it difficult.

UPDATE #2:

Updated to match even more sample data. :D

/^[a-z]+(-[a-z]+)?( [a-z]+(-[a-z]+)?)?$/i

UPDATE #3:

Okay . . . one more update, for the new "one hyphen" requirement. :)

/^[a-z]+(-[a-z]+( [a-z]+)?||( [a-z]+)(-[a-z]+)?)?$/i

Upvotes: 1

ImadOS
ImadOS

Reputation: 425

please try this pattern :

/^[a-z]+\s?[a-z]+\-?[a-z]+$/gim

ok , i updated it for you

DEMO :P

Upvotes: 0

Barmar
Barmar

Reputation: 781078

Try this:

/^[a-z]+(?:-[a-z]+)?(?:\s[a-z]+(?:-[a-z]+)?)$/gim

DEMO

Upvotes: 1

Related Questions