Python:使用 re.match 检查字符串

标签 python regex

我需要编写 func 来检查 str。如果应该满足以下条件:

1) str 应以字母开头 - ^[a-zA-Z]

2) str 可以包含字母、数字、一个 . 和一个 -

3) str 应以字母或数字结尾

4) str 的长度应为 1 到 50

def check_login(str):
    flag = False
    if match(r'^[a-zA-Z][a-zA-Z0-9.-]{1,50}[a-zA-Z0-9]$', str):
        flag = True
    return flag

但应该表示以字母开头,[a-zA-Z0-9.-]长度大于0小于51,以[a-结尾zA-Z0-9]。 如何限制 .- 的数量并将长度限制写入所有表达式?

我的意思是 a - 应该返回 true,qwe123 也应该返回 true。

我该如何解决这个问题?

最佳答案

您将需要前瞻:

^                              # start of string
    (?=^[^.]*\.?[^.]*$)        # not a dot, 0+ times, a dot eventually, not a dot
    (?=^[^-]*-?[^-]*$)         # same with dash
    (?=.*[A-Za-z0-9]$)         # [A-Za-z0-9] in the end
    [A-Za-z][-.A-Za-z0-9]{,49} 
$

参见a demo on regex101.com .

<小时/> 在 Python 中可能是:

import re

rx = re.compile(r'''
^                        # start of string
    (?=^[^.]*\.?[^.]*$)  # not a dot, 0+ times, a dot eventually, not a dot
    (?=^[^-]*-?[^-]*$)   # same with dash
    (?=.*[A-Za-z0-9]$)   # [A-Za-z0-9] in the end
    [A-Za-z][-.A-Za-z0-9]{,49} 
$
''', re.VERBOSE)

strings = ['qwe123', 'qwe-123', 'qwe.123', 'qwe-.-123', '123-']

def check_login(string):
    if rx.search(string):
        return True
    return False

for string in strings:
    print("String: {}, Result: {}".format(string, check_login(string)))

这会产生:

String: qwe123, Result: True
String: qwe-123, Result: True
String: qwe.123, Result: True
String: qwe-.-123, Result: False
String: 123-, Result: False

关于Python:使用 re.match 检查字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309007/

相关文章:

python - 使用两个张量向量创建 N x M 张量矩阵并为每个 (n,m) 对应用一个函数

javascript - 连字符和下划线永远不应该是连续的,但可以在字符串中多次出现

javascript - 如果部分匹配,则正则表达式选择整个单词

python - 如何检测双字节数字

python - 删除 scrapy python 中的特殊字符

regex - 有空间还是没有空间

python - 值错误: No variables to optimize in GradientDescentOptimizer

python - Cython:numpy 数组的无符号整数索引给出不同的结果

python - 基于多个条件加入两个 Pandas 数据框

python - 如何在 Pandas 中对多个索引下的列重新排序