您将如何验证字符串以检查它是否遵循这种格式?

How would you validate a string to check if it follows this format?

我想检查变量中存储的字符串,用户名是否按以下格式存储:

"a.bcde" 或 "12a.bcde"

句号前可以是一个字母,也可以是两个数字加一个字母。

句号后只能是字母

有效字符串:“a.bcdefghi”,“45z.yxwu”

无效字符串:“1a.bcdef”,“12a.bcde@”

我写了下面的代码

if bool(re.match("..[a-z][.][a-z]+", Username))==True:
      return True
else:
      return False

但是,returns“a.bcde”为假,“12a.bcde@fgh.com”为真

您可以使用

^(?:\d{2})?[a-z][.][a-z]+$
  • ^ 字符串开头
  • (?:\d{2})? 可选匹配 2 位数字
  • [a-z][.] 匹配单个字符 a-z 和 .
  • [a-z]+ 匹配 1+ 个字符 a-z
  • $ 字符串结束

Regex demo | [Python 演示(https://ideone.com/k2Hk81)]

例如

import re

pattern = r"(?:\d{2})?[a-z][.][a-z]+$"
strings = [
    "a.bcde",
    "12a.bcde",
    "a.bcdefghi",
    "45z.yxwu",
    "1a.bcdef",
    "12a.bcde@"
]

for s in strings:
    m = re.match(pattern, s)
    if m:
        print("Match for {0}".format(m.group()))

输出

Match for a.bcde
Match for 12a.bcde
Match for a.bcdefghi
Match for 45z.yxwu