1
votes

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")   
2
First, to test a string don't use re.findall but re.match.Casimir et Hippolyte
Don't make us try to guess which test cases fail. It should be part of your question!Daniel Farrell
@DanFarrell Pass/Fail for each test case was providedPanczerTank

2 Answers

4
votes

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]
0
votes

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