【问题标题】:Extract bucket name from aws s3 url using regex使用正则表达式从 aws s3 url 中提取存储桶名称
【发布时间】:2021-02-09 21:48:06
【问题描述】:

我想从 AWS s3 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 的正则表达式。

【问题讨论】:

    标签: regex go amazon-s3


    【解决方案1】:

    这可行:

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

    翻译:

    从字符串的开头找到直到.s3..s3- 的所有内容,并将其捕获到组#1。

    您的存储桶名称将位于$1

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

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

    【讨论】:

    • 查看我为 s3 URL 提供的正则表达式。存储桶名称也可以有点。
    • @SanjayPrajapat 您应该添加适当的示例。
    • @SanjayPrajapat 如果亚马逊提供了正则表达式,那么您为什么要问这个问题。您是否想了解如何在特定的编程语言中使用它?
    • 添加了适当的例子。
    • 我有 url 列表,如示例所示。我想从中提取存储桶名称。我需要一个可以做到这一点的正则表达式。
    【解决方案2】:

    使用

    ^(.*?)\.s3\b
    

    proof

    说明

    --------------------------------------------------------------------------------
      ^                        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 code sample:

    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])
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多