Unix Environment Variable Reference in GO
Match Unix shell environment variable references in both $VAR and ${VAR} forms.
Try it in the GO tester →Pattern
regexGO
\$\{?([A-Z_][A-Z0-9_]*)\}? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\$\{?([A-Z_][A-Z0-9_]*)\}?`)
input := `Path is $HOME/.config`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
\$ matches the literal dollar sign. \{? optionally matches an opening brace. ([A-Z_][A-Z0-9_]*) captures the variable name: must start with a letter or underscore, followed by letters, digits, or underscores. \}? optionally matches the closing brace.
Examples
Input
Path is $HOME/.configMatches
$HOME
Input
export ${DATABASE_URL}Matches
${DATABASE_URL}
Input
no variables hereNo match
—