Can NewReplacer.Replace do case insensitive string replacement?
r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
If not, what's the best way to do case insensitive string replace in Go?
You can use regular expressions for that:
re := regexp.MustCompile(`(?i)html`)
fmt.Println(re.ReplaceAllString("html HTML Html", "XML"))
Playground: http://play.golang.org/p/H0Gk6pbp2c.
It's worth noting that case is a thing that can be different depending on the language and locale. For example, the capital form of German letter "ß" is "SS". While this doesn't generally influence English texts, this is something to bear in mind when working with multi-lingual texts and programs that need to work them.
A generic solution would be as follows:
import (
"fmt"
"regexp"
)
type CaseInsensitiveReplacer struct {
toReplace *regexp.Regexp
replaceWith string
}
func NewCaseInsensitiveReplacer(toReplace, replaceWith string) *CaseInsensitiveReplacer {
return &CaseInsensitiveReplacer{
toReplace: regexp.MustCompile("(?i)" + toReplace),
replaceWith: replaceWith,
}
}
func (cir *CaseInsensitiveReplacer) Replace(str string) string {
return cir.toReplace.ReplaceAllString(str, cir.replaceWith)
}
And then used via:
r := NewCaseInsensitiveReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))
Here's a link to an example in the playground.
Based on the documentation it does not.
I am not sure about the best way, but you can do this with replace in regular expressions and make it case-insensitive with i
flag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With