Created
June 10, 2022 20:04
-
-
Save jrussellsmyth/7133fec69173dba968b3801e1edf06cf to your computer and use it in GitHub Desktop.
Regex Search / Replace with substitutions in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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