Case insensitive string is replaced with Go

Can NewReplacer.Replace replace case insensitive?

r := strings.NewReplacer("html", "xml")
fmt.Println(r.Replace("This is <b>HTML</b>!"))

      

If not, what's the best way to make case insensitive replace in Go?

+3


source to share


3 answers


You can use regular expressions for this:

re := regexp.MustCompile(`(?i)html`)
fmt.Println(re.ReplaceAllString("html HTML Html", "XML"))

      



Playground: http://play.golang.org/p/H0Gk6pbp2c .

It is worth noting that a case is a thing that can be different depending on the language and language. For example, the capital form of the German letter "ß" is "SS". While this does not generally affect English texts, this must be kept in mind when working with multilingual texts and the programs that need to work with them.

+8


source


Based on the documentation, no .



I'm not sure in the best way, but you can do it with replace in regex and make it case insensitive with the i

flag

+2


source


The general 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 on a playground.

+1


source







All Articles