简体   繁体   中英

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. Jm k
  10. k jm

Invalid matches

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

Try this:

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

DEMO

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

please try this pattern :

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

ok , i updated it for you

DEMO :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM