Search code examples
regexperl

Regex Exact Match - First and Last Name with One Space Between


I am trying to to validate user name input. There should be a first and last name (all alpha chars), each beginning with an uppercase letter, one space between the two names and nothing else at all. Here's my example code:

my $name = "John Smith";

if ( $name !~ /([A-Z]{1})([a-z]+)(\s)([A-Z]{1})([a-z]+){1}/g){
    print "No Match!";
}else{
    print "Match!";
}

The problem is, this matches with "John Smith " or "John Smith Joe". I don't see how my pattern allows for anytthing after the last set of lowercase letters in the second name, yet it does. What am I missing?

Thanks!


Solution

  • The regex can much be simplified as

    ^[A-Z][a-z]+\s[A-Z][a-z]+$
    

    see how the regex matches at http://regex101.com/r/dX2hZ1/1

    • ^ anchors the regex at the start of the string. That is it ensures that the string starts with [A-Z], uppercase

    • [A-Z][a-z]+ matches uppercase followed by any number of lower cases

    • \s matches a single space

    • [A-Z][a-z]+ matches the last name

    • $ anchors the regex at the end of the string. Ensure that nothing followes the last name

    What you got wrong

    The regex ([A-Z]{1})([a-z]+)(\s)([A-Z]{1})([a-z]+){1} matches the first name and last name as expected. But it doesnt consider if anything follows that. The anchor $ ensures that it is not followed by anything else. And the anchor ^ ensures that nothing prescedes the matches string.