use*_*519 1 regex amazon-s3 amazon-web-services
从 aws doc https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html,我们知道允许作为对象名称一部分的字符。我想构建一个正则表达式,它应该指定一个对象或一组对象,如下所示:
/abc/obj*
/abc/*
/*
/abc/obj1.txt
Run Code Online (Sandbox Code Playgroud)
我创建的正则表达式如下所示:
"((/[a-zA-Z0-9]+)*((/[a-zA-Z0-9\\.]*(\\*)?)?))"
Run Code Online (Sandbox Code Playgroud)
除了需要在方括号内添加的额外符号外,这个正则表达式看起来不错还是需要更多的增强或简化?
首先,您的正则表达式不太适用。/abc/obj.txt例如,对于 case ,它无法匹配.txt部分。请参阅您的正则表达式演示。其次,在 sub-expression 中[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}')
Run Code Online (Sandbox Code Playgroud)
印刷:
/abc/obj* match = True
/abc/* match = True
/* match = True
/abc/obj1.txt match = True
Run Code Online (Sandbox Code Playgroud)

但是当我在https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html阅读对象键规范时,您的测试用例似乎不是有效示例,因为那里没有显示任何示例有主角/。似乎该*角色应该像任何其他角色一样对待,并且可以在任何位置出现多次。这使得正则表达式实际上要简单得多:
^[a-zA-Z0-9!_.*'()-]+(/[a-zA-Z0-9!_.*'()-]+)*$
Run Code Online (Sandbox Code Playgroud)
新代码:
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}')
Run Code Online (Sandbox Code Playgroud)
印刷:
abc match = True
-/abc/(def)/!x*yz.def.hij match = True
Run Code Online (Sandbox Code Playgroud)