大写,小写和数字的正则表达式

发布于 2025-02-06 19:43:05 字数 470 浏览 0 评论 0原文

我的任务是验证一个必须包含至少一个小写和大写字符的字符串以及至少一个数字。我不必检查此字符串的长度。

我正在尝试做这样的事情:

from re import match


regexp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"
string_to_validate = input("Write string with uppercase/lowercase characters and numbers.")
if not match(regexp, string_to_validate):
    raive ValueError("You should use uppercase and lowercase characters with numbers in your string")

但是在我看来,为此目的有一个表达式比那个目的要好得多。老实说,我什至不知道表达开始时的符号'^'是什么。

My task is to validate a string that must contain at least one lowercase and uppercase character and at least one number. I don't have to check the length of this string.

I'm trying to do something like this:

from re import match


regexp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"
string_to_validate = input("Write string with uppercase/lowercase characters and numbers.")
if not match(regexp, string_to_validate):
    raive ValueError("You should use uppercase and lowercase characters with numbers in your string")

But it seems to me that there's an expression for this purpose that is much better than that one. Honestly, I don't even know what the symbol '^' at the beginning of the expression is used for.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹过旳痕迹 2025-02-13 19:43:05

将需求分解为单个正则是更可维护的,更可读性,并且使用 re.search

import re

strs = ['Bb2', 'Bb', 'b2', 'B2']
for s in strs:
    if not (re.search(r'[A-Z]', s)
            and re.search(r'[a-z]', s)
            and re.search(r'\d', s)):
        print(f'Input "{s}" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.')
    else:
        print(f'Input "{s}" is OK')
# Input "Bb2" is OK
# Input "Bb" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "b2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "B2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.

It is more maintainable and more readable to break up the requirements into individual regexes, and to use re.search:

import re

strs = ['Bb2', 'Bb', 'b2', 'B2']
for s in strs:
    if not (re.search(r'[A-Z]', s)
            and re.search(r'[a-z]', s)
            and re.search(r'\d', s)):
        print(f'Input "{s}" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.')
    else:
        print(f'Input "{s}" is OK')
# Input "Bb2" is OK
# Input "Bb" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "b2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "B2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文