I am looking for a regular expression to check names. I have searched the net and also used the suggestion that were given me by StackOverflow while posting this question.
I also know it’s possible in stages, but I’m looking for a regex-1-liner to keep my code clean, simple and most important: fast.
What do I need:
A regular expression that checks names of people while they are registering to my site. I want to allow names as:
- Name
- Name surename
- Name O’brian
- Name surename secondarysurname
- Name surename-surnametwo
- N. Surename
But I don’t want to allow names as:
- Name (double spacebar)
- Name — surename (double minus)
- Name–‘ (just bullshit)
Well, I think you understand what I mean and what I don’t want to allow.
I only want to use a-zA-Z and – . ‘
I think that’s the only thing I need to allow. The – . ‘ signs can only be used once between or after a word. Since a name like ‘name O”Brian’ does not exist.
But a name like ‘Name surename secondary-thirdsurname’ should be allowed. So one spacebar and one minus sign.
I came up with several regex’ using http://public.kvalley.com/regex/regex.asp and other regex programs. But I’m just a noob with regex’.
I hope somebody knows a lot about regular expressions and is willing to help me. Because at the moment.. I’m stuck 🙁
Thanks in advance,
Jelmer
ps. If you have any questions regarding my question. Please ask them because I’d really like to have your help!
A general rule of thumb that applies to many aspects of coding, but especially to regex design, is, your code can be:
Pick two.
In addition to that, I guarantee that a one-liner this complex will never be clean. Break it up into regex variables and comment it liberally. Later on, you’ll be thankful that you did! While you’re at it, turn it into a generic name validator class that you can reuse. While Perl can be quite munged by experts into something totally unholy, it’s beauty often comes out when we follow the same laws of politeness and cleanliness that we follow in other, more structured languages.
TL;DR: Don’t make it a one-liner. Please.