Skip to content

Instantly share code, notes, and snippets.

@nmarley
Created December 12, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmarley/a887c2ced33928822243c918ecd6d364 to your computer and use it in GitHub Desktop.
Save nmarley/a887c2ced33928822243c918ecd6d364 to your computer and use it in GitHub Desktop.
Go basic recursion on string parts
package main
import (
"fmt"
"os"
"regexp"
"strings"
)
var reS3KeyPDFUpload = regexp.MustCompile(`^.*\/(?P<year>\d{4})\/(?P<month>\d{2})\/(?P<day>\d{2})\/.*\.pdf$`)
func main() {
key := "xyz/2019/12/06/2019_12_06_SOMETHING.pdf"
if !reS3KeyPDFUpload.MatchString(key) {
fmt.Fprintf(os.Stderr, "key [%s] does not match pattern\n", key)
os.Exit(1)
}
res := reS3KeyPDFUpload.FindStringSubmatch(key)
fmt.Printf("%+v\n", res)
pre := getS3PrefixesToIndex(key)
fmt.Printf("s3 Prefixes: %+v\n", pre)
}
var iter = 0
func basicRecursion(sections []string, prefix string) []string {
iter++
fmt.Printf("iter = %v\n", iter)
fmt.Printf("len(sections) = %d\n", len(sections))
var list []string
head := sections[0]
tail := sections[1:]
if len(prefix) > 0 {
head = fmt.Sprintf("%v/%v", prefix, head)
}
list = append(list, head)
if len(tail) > 0 {
l2 := basicRecursion(tail, head)
return append(list, l2...)
}
return list
}
func getS3PrefixesToIndex(s3Key string) []string {
sections := strings.Split(s3Key, "/")
return basicRecursion(sections[:len(sections)-1], "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment