【问题标题】:Validate string value in Python [duplicate]在 Python 中验证字符串值 [重复]
【发布时间】:2019-10-13 14:47:02
【问题描述】:

我在玩 Python。我尝试验证变量值。应该超级简单,但我很挣扎。以下是请求:

  1. 值必须正好有 3 个字符 = +49
  2. 值必须完全符合格式 = +49

我试图循环遍历字符串变量。我使用了一个 for 循环。我还尝试将值保存在数组中,稍后再检查数组。

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

我现在将开始使用 if 语句检查数组,但我没有说到重点,因为我似乎已经走错路了。

【问题讨论】:

  • 输入是什么,预期输出是什么?我没有得到req的
  • 你没有增加你的 i 值?

标签: python regex string validation


【解决方案1】:

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

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

Demo

测试

import re

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

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

print(matches)

输出

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

正则表达式电路

jex.im 可视化正则表达式:


如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在 this link 中观看它如何与一些示例输入匹配。


【讨论】:

  • 哇,艾玛!!!非常感谢,收藏了!
【解决方案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"))

【讨论】:

  • 大家好 - 首先非常感谢您的回答。 @Wimanicesir,这可能是关键答案。我会玩弄的。顺便说一句 - 有人将问题标记为“重复”。我需要做什么?我之前找不到这个问题的答案。
  • 非常感谢 - 我想我可以处理这些信息。但目前我收到以下错误: if not isinstance(int(x[2]), int): ValueError: invalid literal for int() with base 10: 'n' I'v enter the Value "+2n"用于测试目的。 n 是一个字符,我希望“返回 false”而不是错误消息。
  • 没问题!关于这个问题,我会编辑。等一下。 :)
  • 嗨,孙先生,我添加了一些错误处理,因此它不会在非整数输入时崩溃。我不知道你是否有能力解除重复标记。
  • 哇——这让我大吃一惊!它有效...非常感谢。
猜你喜欢
  • 2012-10-02
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多