regex - Amazon S3 对象名称的正则表达式

标签 regex amazon-web-services amazon-s3

来自 aws 文档 https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html ,我们知道允许作为对象名称一部分的字符。我想构建一个正则表达式来指定一个对象或一组对象,如下所示:

/abc/obj*
/abc/*
/*
/abc/obj1.txt

我创建的正则表达式如下所示:

"((/[a-zA-Z0-9]+)*((/[a-zA-Z0-9\\.]*(\\*)?)?))"

除了需要在方括号内添加额外的符号外,这个正则表达式看起来不错还是需要更多的增强或简化?

最佳答案

首先,您的正则表达式不太适用。例如,对于/abc/obj.txt 的情况,它无法匹配.txt 部分。参见 A demo of your regex .其次,在子表达式[a-zA-Z0-9\\.]中,不需要反斜杠字符; . 将被解释为没有它们的句点字符。第三,您应该在正则表达式的开头有 ^ ,在正则表达式的末尾有 $ ,以确保您匹配所需的内容,并且输入中没有额外的内容。第四,您没有指定您使用的语言。

我在这里使用 Python:

import re

tests = [
    '/abc/obj*',
    '/abc/*',
    '/*',
    '/abc/obj1.txt'
]

# the regex: ^/([a-zA-Z0-9]+/)*(\*|([a-zA-Z0-9]+(\*|(\.[a-zA-Z0-9]+)?)))$

for test in tests:
    m = re.match(r"""
        ^                   # the start of the string
        /                   # a leading /
        ([a-zA-Z0-9]+/)*    # 0 or more: abc/
        (\*                 # first choice: *
        |                   # or
        ([a-zA-Z0-9]+       # second choice: abc followed by either:
            (\*|(\.[a-zA-Z0-9]+)?)))    # * or .def or nothing
        $                   # the end of the string
        """, test, flags=re.X)
    print(test, f'match = {m is not None}')

打印:

/abc/obj* match = True
/abc/* match = True
/* match = True
/abc/obj1.txt match = True

Regex Demo

Analysis of the regex

但是当我在 https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html 阅读对象键的规范时,您的测试用例似乎不是有效示例,因为那里显示的示例都没有前导 / 字符。看起来 * 字符应该像对待任何其他字符一样对待,并且可以在任何位置出现多次。这实际上使正则表达式简单得多:

^[a-zA-Z0-9!_.*'()-]+(/[a-zA-Z0-9!_.*'()-]+)*$

enter image description here

Regex Demo

新代码:

import re

tests = [
    'abc',
    '-/abc/(def)/!x*yz.def.hij'
]

# the regex: ^[a-zA-Z0-9!_.*'()-]+(/[a-zA-Z0-9!_.*'()-]+)*$

for test in tests:
    m = re.match(r"""
        ^                       # the start of the string
        [a-zA-Z0-9!_.*'()-]+    # 1 or more: ~abc*(def)
        (
            /
            [a-zA-Z0-9!_.*'()-]+
        )*                      # 0 or more of /~abc*(def)
        $                       # the end of the string
        """, test, flags=re.X)
    print(test, f'match = {m is not None}')

打印:

abc match = True
-/abc/(def)/!x*yz.def.hij match = True

关于regex - Amazon S3 对象名称的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58712045/

相关文章:

python - 查找字符串的所有出现位置,除非在另一个模式中找到该字符串

Java 正则表达式匹配直到字符

python - 使用正则表达式提取特定单词后跟特定语法(例如括号)

javascript - 如何替换正则表达式中的变量

c# - 如何禁用默认的 AWS Lambda 日志记录?

ios - 适用于 iOS 的 AWS S3 SDK v2 - 将图像文件下载到 UIImage

amazon-web-services - 预提交钩子(Hook)获取 "E0000 Template needs to be an object."

amazon-web-services - S3 通知 SQS 是否可能失败?

amazon-s3 - CloudFormation 支持 "Expired Object Delete Marker"

amazon-s3 - 防止机器人创建多个免费帐户和上传文件