Is there any way to known which condition in re.fullmatch wasn't met?

Viewed 55

I need to check if the string fulfil the conditions:

  • at least 4 characters
  • must consist of only letters
  • at least 1 upper letter

I've got:

if not re.fullmatch(r'^(?=.*[A-Z])(?=.*[a-z]).{4,}$', 'ab7c'):
   print('The string is wrong')

May I know which conditions were not met? In my example, they are:

  • must consist of only letters
  • at least 1 upper letter
1 Answers

Well you could just perform each assertion separately:

def checkString(input):
    msg = ''
    if len(input) < 4:
        msg = '  -length must be 4 or more characters'
    if re.search(r'[^A-Za-z]', input):
        msg = msg + '\n  -input must consist of only letters'
    if not re.search(r'[A-Z]', input):
        msg = msg + '\n  -input must have at least one uppercase letter'

    if msg:
        print('The input fails validation:\n  ' + msg.strip())

checkString('ab7')

This prints:

The input fails validation:
  -length must be 4 or more characters
  -input must consist of only letters
  -input must have at least one uppercase letter

However, if the input be missing just one criterion, then we would get:

checkString('ABC3')

The input fails validation:
  -input must consist of only letters
Related