2

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()
2
  • 1
    This [a-zA-Z a-zA-Z] is the same as [a-zA-Z ] (Note that names can have a great variety in length and characters) Commented Oct 21, 2021 at 18:17
  • Does r"(\w+)\s+(\w+)" work for you? Commented Oct 21, 2021 at 18:20

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.