Replace text in strings

suggest change

Replace string with strings.Replace

	s := "original string original"
	s2 := strings.Replace(s, "original", "replaced", -1)
	fmt.Printf("s2: '%s'\n", s2)
s2: 'replaced string replaced'

The last argument of strings.Replace is the maximum number of replacements. -1 means replace all. strings.ReplaceAll is the same call with that count.

Replace string with a regular expression

	s := "original string original"
	rx := regexp.MustCompile("(?U)or.*al")
	s2 := rx.ReplaceAllString(s, "replaced")
	fmt.Printf("s2: '%s'\n", s2)
s2: 'replaced string replaced'

This shows how to replace text with a regular expression. (?U)or.*al is a non-greedy ((?U) flag) expression that matches original.

We replace all parts of the string matching the regex with a string replaced.

The expression is non-greedy, so it matches the shortest string. The default is greedy and matches the longest string.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents