Reputation: 71
Regular expression to match single first name string or first and last name string with one space and one hyphen.
Valid matches
Invalid matches
Upvotes: 0
Views: 123
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:
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