[英]Extract bucket name from aws s3 url using regex
I want to extract the bucket name from AWS s3 URLs.我想从 AWS s3 URL 中提取存储桶名称。
URLs can be in many formats. URL 可以有多种格式。 Below is the list of regex for supported s3 URLs:
以下是支持的 s3 URL 的正则表达式列表:
[a-z0-9.-]+\.s3\.amazonaws\.com
[a-z0-9.-]+\.s3-[a-z0-9-]+\.amazonaws\.com
[a-z0-9.-]+\.s3\.[a-z0-9-]+\.amazonaws\.com
[a-z0-9.-]+\.s3-website[.-](eu|ap|us|ca|sa|cn)
Example:例子:
bucket-name.s3.us-west-2.amazonaws.com
bucket.name.s3.us-west-2.amazonaws.com
bucket-name.s3-us-west-2.amazonaws.com
bucket.name.s3-us-west-2.amazonaws.com
bucket-name.s3.amazonaws.com
bucket.name.s3.amazonaws.com
I want a single regex that can extract bucket-name
from these URLs in GoLang
.我想要一个可以从
GoLang
中的这些 URL 中提取bucket-name
的正则表达式。
This would work:这会起作用:
^(.+)(?:\.s3[-.].*)$
Translated:翻译:
From the beginning of the string find everything leading up to
.s3.
从字符串的开头找到通向
.s3.
or.s3-
and capture it into group #1.或
.s3-
并将其捕获到第 1 组中。
Your bucket name will be in $1
.您的存储桶名称将在
$1
中。
See the regex101 link below and use the code generator to see a Golang example.请参阅下面的 regex101 链接并使用代码生成器查看 Golang 示例。
https://regex101.com/r/LRvA5F/1 https://regex101.com/r/LRvA5F/1
Use采用
^(.*?)\.s3\b
Explanation解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
s3 's3'
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
package main
import (
"fmt"
"regexp"
)
func main() {
r := regexp.MustCompile(`^(.*?)\.s3\b`)
str := "bucket-name.s3.us-west-2.amazonaws.com"
match := r.FindStringSubmatch(str)
fmt.Println(match[1])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.