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

12,847

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.

Share:
12,847

Related videos on Youtube

DonC
Author by

DonC

Updated on September 18, 2022

Comments

  • DonC
    DonC over 1 year

    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!

  • sshashank124
    sshashank124 over 9 years
    You should explain why his method wasn't working and how your addition of ^$ fixes it. But good answer
  • nu11p01n73R
    nu11p01n73R over 9 years
    @sshashank124 just adding details to the answer. Thank you for the guidance :)
  • bytepusher
    bytepusher over 9 years
    I don't mean to spoil the party, but be aware there are names that do not follow your pattern, for example "Paul McCartney" or some scottish names. Also, you may have to beware of utf8 when allowing international users.
  • DonC
    DonC over 9 years
    @nu11p01n73R Thanks for the explanation and help!