1

I'm playing with Python. I try to validate a variable value. Should be super simple but I'm struggling. Here are the req's:

  1. Value must have exactly 3 char = +49
  2. Value must have exactly the format = +49

I tried to loop through the string variable. I used a for loop. I also tried to save the values in an array and check the array later on.

def validateCountryCode(self):
        val = ["1", "2", "3"]
        i = 0
        for val[i] in self.countryCode
            print(val[i])
            val[i] += 1

I would now start to check the array with an if-statement but I don't get to the point because it seems that I already went the wrong way.

Mr.Sun
  • 19
  • 4

2 Answers2

1

Maybe, this simple expression might work OK:

^[+][0-9]{2}$

Demo

Test

import re

expression = r'^[+][0-9]{2}$'
string = '''
+00
+49
+99
+100
'''

matches = re.findall(expression, string, re.M)

print(matches)

Output

['+00', '+49', '+99']

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Emma
  • 1
  • 9
  • 28
  • 53
0

I wrote the most simple validator I could imagine:

def validateCountryCode(countrycode):

  # Check if countrycode is exact 3 long
  if len(countrycode) != 3:
    return False

  # CHECK FORMAT
  # Check if it starts with +
  if countrycode[0] != "+":
    return False

  # Check second and third character is int
  try: 
      int(countrycode[1])
      int(countrycode[2])
  except ValueError:
      return False


  # All checks passed!
  return True


# True
print(validateCountryCode("+32"))

# False
print(validateCountryCode("332"))

# False
print(validateCountryCode("+2n"))
Wimanicesir
  • 3,428
  • 2
  • 9
  • 23
  • hi all - first of all many thanks for answering. @Wimanicesir, this could be the keyanswer. I will paly around with that. by the way - someone marked the question as "duplicate". What do I have to do? I couldn't find a answer to the question before. – Mr.Sun Oct 13 '19 at 15:27
  • Many thanks - I think I can work with the information. but currently I'm getting the following error: if not isinstance(int(x[2]), int): ValueError: invalid literal for int() with base 10: 'n' I'v entered the Value "+2n" for testing purpose. n is a char and I would expect "return false" instead of the error message. – Mr.Sun Oct 13 '19 at 15:58
  • No problem! About the problem, I will edit. Just a second. :) – Wimanicesir Oct 13 '19 at 15:59
  • Hey Mr. Sun, I added some error handling so it won't crash on non integer input. I don't know if you have the power to unlift the duplicate marking. – Wimanicesir Oct 13 '19 at 16:02
  • Wow - that blew me away! It works... many many thanks. – Mr.Sun Oct 13 '19 at 16:24