1

I want to return true if name is valid. Name can contain:

  1. upper or lower case characters
  2. no numbers or special characters
  3. can be one or two words with a single space in the middle
  4. first name and last name can be between 2-25 characters each

eg.

  • John Smith = true
  • John = true
  • JoHn = true
  • John Sm1th = false
  • John $mith = false
  • J0hn = false
  • John Smith = false (two spaces between names)

Here is my code thus far. It fails some of these test cases.

import re

if re.findall('[A-Za-z]{2,25}\s[A-Za-z]{2,25}', string):
    print("true")
else:
    print("false")   
3
  • 1
    First, to test a string don't use re.findall but re.match. Commented Dec 18, 2017 at 22:13
  • Don't make us try to guess which test cases fail. It should be part of your question! Commented Dec 18, 2017 at 22:39
  • @DanFarrell Pass/Fail for each test case was provided Commented Dec 18, 2017 at 22:48

2 Answers 2

5

To match one or two words, you need to make either the first name or the last name optional, also you need anchors to assure it's not partial matching or use re.fullmatch instead of re.findall:

lst = ['John Smith', 'John', 'JoHn', 'John Sm1th', 'John $mith', 'J0hn', 'John  Smith']

import re
[re.fullmatch('[A-Za-z]{2,25}( [A-Za-z]{2,25})?', x) for x in lst]
# [<_sre.SRE_Match object; span=(0, 10), match='John Smith'>, <_sre.SRE_Match object; span=(0, 4), match='John'>, <_sre.SRE_Match object; span=(0, 4), match='JoHn'>, None, None, None, None]

Convert result to bool:

[bool(re.fullmatch('[A-Za-z]{2,25}( [A-Za-z]{2,25})?', x)) for x in lst]
# [True, True, True, False, False, False, False]
Sign up to request clarification or add additional context in comments.

5 Comments

Where [A-Za-z] can be shortened as [A-z]
@albert: no it's wrong, look at the ascii table to see all characters between A and z. However, you can use [a-z] with the re.I flag.
@albert You actually can't, see this answer.
is there any practical difference between a regex of " " and "\s"?
@WoodyPride \s can match normal white space, tab \t and new line characters \n or \r on windows while " " only matches normal white space.
0

'[A-Za-z]{2,25}||\s[A-Za-z]{2,25}' this should work. You can test your regular expressions at https://pythex.org/

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.