#development #golang #pattern

Today, I'll show you how to do a case-insensitive string replace in Go.

By default, string replacement in Go is case-sensitive, but sometimes, that's not the desired behaviour.

The best way to tackle this problem is to use the regexp (regular expressions) package to do this.

You can do it with a simple function like this:

1import (
2    "regexp"
3)
4
5func CaseInsensitiveReplace(subject string, search string, replace string) string {
6    searchRegex := regexp.MustCompile("(?i)" + search)
7    return searchRegex.ReplaceAllString(subject, replace)
8}

The trick is in the regular expression pattern. The modifier i tells it to be case-insensitive.

This works flawlessly, however, there is one caveat: performance.

To give you an idea about the performance penalty, I wrote a simple benchmark:

 1import (
 2    "testing"
 3)
 4
 5func Benchmark_CaseInsensitiveReplace(b *testing.B) {
 6    for n := 0; n < b.N; n++ {
 7        twxstring.CaseInsensitiveReplace("{Title}|{Title}", "{title}", "My Title")
 8    }
 9}
10
11func Benchmark_CaseSensitiveReplace(b *testing.B) {
12    for n := 0; n < b.N; n++ {
13        strings.ReplaceAll("{Title}|{Title}", "{Title}", "My Title")
14    }
15}

The results are pretty self-explanatory:

Benchmark_CaseInsensitiveReplace-4         420237          3384 ns/op        2119 B/op          24 allocs/op
Benchmark_CaseSensitiveReplace-4          8224800           190 ns/op          64 B/op           2 allocs/op