Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive string replace in Go

Tags:

string

replace

go

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?

like image 861
xpt Avatar asked Jul 10 '15 19:07

xpt


3 Answers

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.

like image 120
Ainar-G Avatar answered Nov 18 '22 10:11

Ainar-G


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.

like image 37
jabclab Avatar answered Nov 18 '22 10:11

jabclab


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

like image 39
Salvador Dali Avatar answered Nov 18 '22 09:11

Salvador Dali