skip to content
Alvin Lucillo

Go Regex

/ 1 min read

Using regex in Go is straightforward. You can find a match and get the result of a capture group. In the example below, the program is looking for the name and its alias. The regex finds any text that has square brackets. MatchString checks if the text matches the regex, and FindStringSubmatch returns the original text and its capture groups as an array. The length of the result depends on the number of capture groups.

func main() {
	name := "julia [jules]" // name with alias
	re := regexp.MustCompile(`^(.+?) \[(.+)\]$`)

	if re.MatchString(name) {
		match := re.FindStringSubmatch(name)
		fmt.Println(strings.Join(match, ",")) // julia [jules],julia,jules
	}
}