在Python中验证字符串值

在Python中验证字符串值,python,regex,string,validation,Python,Regex,String,Validation,我在玩Python。我尝试验证一个变量值。应该非常简单,但我正在努力。以下是请求: 值必须正好有3个字符=+49 值的格式必须正好为=+49 我试图循环遍历字符串变量。我用了一个for循环。我还尝试将值保存在数组中,稍后再检查数组 def validateCountryCode(self): val = ["1", "2", "3"] i = 0 for val[i] in self.countryCode print(va

我在玩Python。我尝试验证一个变量值。应该非常简单,但我正在努力。以下是请求:

  • 值必须正好有3个字符=+49
  • 值的格式必须正好为=+49
  • 我试图循环遍历字符串变量。我用了一个for循环。我还尝试将值保存在数组中,稍后再检查数组

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

    我现在开始用if语句检查数组,但我没有说到点子上,因为我似乎已经走错了方向。

    也许,这个简单的表达式可以正常工作:

    ^[+][0-9]{2}$
    
    试验 输出 正则表达式电路 可视化正则表达式:


    如果您希望简化/修改/探索表达式,将在的右上面板中进行解释。如果您愿意,还可以在中查看它与一些示例输入的匹配情况



    我编写了我能想象到的最简单的验证器:

    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"))
    

    什么是输入,什么是预期输出?我没有得到要求“你不增加你的i值吗?大家好-首先非常感谢您的回答@Wimanicesir,这可能是关键答案。我会带着它到处玩的。顺便说一下,有人把这个问题标为“重复”。我该怎么办?我以前找不到这个问题的答案。非常感谢-我想我可以处理这些信息。但目前我得到了以下错误:if not isinstance(int(x[2]),int):ValueError:int()的文本无效,以10为基数:“n”I'v输入值“+2n”用于测试。n是一个字符,我希望“returnfalse”而不是错误消息。没问题!关于这个问题,我将编辑。请稍等。:)嘿,孙先生,我添加了一些错误处理,这样它就不会在非整数输入时崩溃。我不知道你是否有能力取消复制标记。哇-这让我大吃一惊!它是有效的。。。非常感谢。哇,艾玛!!!非常感谢,把它加入书签!
    ['+00', '+49', '+99']
    
    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"))