Extract bucket name from aws s3 url using regex

Viewed 1347

I want to extract the bucket name from AWS s3 URLs.

URLs can be in many formats. Below is the list of regex for supported s3 URLs:

[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.

2 Answers

This would work:

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

Translated:

From the beginning of the string find everything leading up to .s3. or .s3- and capture it into group #1.

Your bucket name will be in $1.

See the regex101 link below and use the code generator to see a Golang example.

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

Use

^(.*?)\.s3\b

See proof.

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

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