繁体   English   中英

使用正则表达式从 aws s3 url 中提取存储桶名称

[英]Extract bucket name from aws s3 url using regex

我想从 AWS s3 URL 中提取存储桶名称。

URL 可以有多种格式。 以下是支持的 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)

例子:

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

我想要一个可以从GoLang中的这些 URL 中提取bucket-name的正则表达式。

这会起作用:

^(.+)(?:\.s3[-.].*)$

翻译:

从字符串的开头找到通向.s3. .s3-并将其捕获到第 1 组中。

您的存储桶名称将在$1中。

请参阅下面的 regex101 链接并使用代码生成器查看 Golang 示例。

https://regex101.com/r/LRvA5F/1

采用

^(.*?)\.s3\b

证明

解释

--------------------------------------------------------------------------------
  ^                        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

Go 代码示例

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM