python - 如何编写一个Python正则表达式来确保字符不在模式的特定位置?

标签 python python-3.x regex python-3.8

我正在尝试编写一个验证用户名的正则表达式,其中一个要求是,如果字符串中有数字,则数字必须位于字母之后,并且第一个数字不能为零。由于某种原因,我无法让它使包含一组以零开头的数字的字符串无效

username_pattern = r'^[a-z]{3}[a-z]*([1-9]*|[1-9]*[0-9]*)'
if not re.fullmatch(username_pattern, test_username):
    raise ValueError('username may have numbers but they must be after all the letters and may not being with 0')

我期望像“abc123”这样的东西可以工作,但是“abc0123”会失败,而且它们都可以工作。

最佳答案

您可以使用 r'^[a-z]{3,}([1-9]+[0-9]*)?' 代替。 说明-

  1. [a-z]{3,} 将匹配 a-z 至少 3 次,这是 [a-z]{3}[a-z]* 的较短版本 您当前正在使用的。
  2. ([1-9]+[0-9]*) 将确保至少有 1 个来自 1-9 的字符(+ 表示至少应匹配一个字符),后跟任意数量的 0-9 字符。
  3. 最后使用 ? 将数字组设为可选

您可以尝试上面的正则表达式 here .

这是一个显示各种用户名的简单示例 -

import re
users = ['xyz123', 'xyz1234', 'xyz01', 'abdcd213', 'xy1234']
username_pattern = r'^[a-z]{3}[a-z]*([1-9]+[0-9]*)?'
for user in users:
    if not re.fullmatch(username_pattern, user):
        print(f'Invalid user: {user}')

输出:

Invalid user: xyz01
Invalid user: xy1234

关于python - 如何编写一个Python正则表达式来确保字符不在模式的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74827501/

相关文章:

javascript - 小书签中的字符串操作与控制台中的行为不同

python - super() 为新式类引发 "TypeError: must be type, not classobj"

Python重命名重复项

python - 如何避免温度脚本中的全局变量?

python - 比较 2 个 CSV 文件内的列

c# - 如何检查字符串是否包含列表值,如果包含但具有其他值,则如何单独检查

python - 如何注销 Django 中的用户?

python-3.x - 我可以压缩此代码以根据变量制作多个标签和条目吗?

python-3.x - PyQt/PySide 如何在将 QGraphicsItem 添加到 QGraphicsScene 后访问/移动它

javascript - 密码正则表达式 - 不起作用