当字符串名与列表中的任何元素部分匹配时,将其排除在外

2024-06-16 10:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python3读取AWS bucket名称,如果bucket名称与bucket_exclusion_list数组中定义的任何名称部分匹配,则明确退出循环

我创建了一个bucket验证函数,如下所示:

def valid_bucket(bucket_name):
    bucket_exclusion_list = ['do-not-delete', 'aws-config', 'elasticbeanstalk']
    for exclusion_items in bucket_exclusion_list:
        if bool(re.match(exclusion_items, bucket_name)) == True:
            return False
        else:
            continue
    return True

在我的main函数中,我调用valid_bucket函数并基于布尔值,在代码中继续

if valid_bucket(bucket_name):
   bucket_info["bucketName"] = bucket_name
   bucket_info["bucketSize"] = ''
   ...

代码似乎没有按预期工作。如果当前bucket名称与排除列表中的项目匹配,我必须转到下一个bucket名称。有人能帮我理解代码的问题吗


Tags: 函数代码nameinfo名称awstruereturn
2条回答

只需按以下方式更改您的功能:

import re
def valid_bucket(bucket_name):
    bucket_exclusion_list = ['do-not-delete', 'aws-config', 'elasticbeanstalk']
    regex = "|".join(bucket_exclusion_list)
    if re.search(rf'{regex}', bucket_name):
        return True
    return False

if (valid_bucket(bucket_name)):
    print ("VALID")
else:
    print ("INVALID")

bucket name=my-bucket的输出

INVALID

bucket name=do-not-delete my-bucket的输出

VALID

re.match将只匹配字符串的开头。您可以使用in代替正则表达式:

if exclusion_items in bucket_name:
    return False
else:
    continue

也就是说,该函数可以重写为:

def valid_bucket(bucket_name):
    bucket_exclusion_list = ['do-not-delete', 'aws-config', 'elasticbeanstalk']
    return all(item not in bucket_name for item in bucket_exclusion_list)

相关问题 更多 >