Skip to content

Instantly share code, notes, and snippets.

@jrussellsmyth
Created June 10, 2022 20:04
Show Gist options
  • Select an option

  • Save jrussellsmyth/7133fec69173dba968b3801e1edf06cf to your computer and use it in GitHub Desktop.

Select an option

Save jrussellsmyth/7133fec69173dba968b3801e1edf06cf to your computer and use it in GitHub Desktop.
Regex Search / Replace with substitutions in Go
// https://go.dev/play/p/XPjAjsNm_2H
package main
import (
"fmt"
"regexp"
)
func main() {
source := "http://some.dumb.domain/path/to/resource/12345"
regex := "^(?P<scheme>(http)|(https))://(?P<host>[^/]+)(?P<path>/.*/)(?P<id>[^/]+)$"
template := "From Source - scheme:${scheme} host:${host} path:${path} id:${id} or 1:${1} 4:${4} 5:${5} 6:${6}"
rxp := regexp.MustCompile(regex)
var result string
if matches := rxp.FindStringSubmatchIndex(source); len(matches) > 0 {
result = string(rxp.ExpandString(nil, template, source, matches))
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment