Home > Enterprise >  python name regex
python name regex

Time:10-22

Am trying to match a name in the pattern "FirstnameSpaceLastname" e.g John Doe, just the first and last name with a space in between, how can I go about it? the code is below shows what i.ve tried:

user_input = input("Enter you full names: ")
def valid_name():
    #name_regex = re.compile('^[a-zA-Z\\sa-zA-Z]$')
    #name_regex = re.compile('^[a-zA-Z]\s[a-zA-Z]$')
    #name_regex = re.compile('^[a-zA-Z a-zA-Z] $')
    #name_regex = re.compile('^a-zA-Z\sa-zA-Z$')    
    name_regex = re.compile('^[a-zA-Z a-zA-Z]$')
    nameMatch = re.match(name_regex, user_input)
    if nameMatch:
        print(user_input)
    else:
        print('Enter name in (Firstname Lastname) format')

valid_name()

CodePudding user response:

Have you tried to compile:

[a-zA-Z] \s[a-zA-Z] 

?

About @JonSG's comentary: \w is for any alphanumeric. Replace it with a-zA-Z if you need only letters.

CodePudding user response:

Use

^[^\W\d_] \s[^\W\d_] \Z

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^\W\d_]                 any character of: letters/diacritics (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  [^\W\d_]                 any character of: letters/diacritics (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string
  • Related