Replace and split with regex
Replace and split with regex
ReplaceAllString replaces every non-overlapping match and expands capture references in the replacement. Use ${1} or ${name} to clearly delimit the group reference. ReplaceAllLiteralString treats the replacement as ordinary text; Split divides a string at regex matches.
package main
import ( "fmt" "regexp")
func main() { r := regexp.MustCompile(`([a-z]+)=([0-9]+)`) fmt.Println(r.ReplaceAllString("tea=2 rice=3", `${1}: ${2}`)) fmt.Println(r.ReplaceAllLiteralString("tea=2", `$1`))}The first replacement reorders the representation of fields while retaining the values. The second prints a literal dollar sign and digit. If replacement text comes from a user and should not be a template, choose the literal method. For plain fixed substrings strings.ReplaceAll is simpler.
Expected output:
tea: 2 rice: 3$1Split on variable separators
package main
import ( "fmt" "regexp")
func main() { r := regexp.MustCompile(`[,; ]+`) fmt.Printf("%q\n", r.Split("tea, rice;milk", -1)) fmt.Printf("%q\n", r.Split("tea, rice;milk", 2))}A negative n requests all pieces; positive n limits the number of pieces, leaving the remainder intact in the last one. Zero returns nil. Leading or trailing separators may create empty pieces. This is not a CSV parser: quoted delimiters require format-aware parsing.
Expected output:
["tea" "rice" "milk"]["tea" "rice;milk"]Try it locally
Convert consecutive spaces or tabs to one space in the string tea rice milk (where is a tab). Print the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 03: Replace and split with regex
Check the lesson objective before moving on.
Which method keeps `$1` literal in replacement text?
What does Split(s,2) limit?