Skip to content

Instantly share code, notes, and snippets.

@alex-ant
Created December 16, 2020 06:43
Show Gist options
  • Save alex-ant/405f3a4be184ea16e5449135d578a49a to your computer and use it in GitHub Desktop.
Save alex-ant/405f3a4be184ea16e5449135d578a49a to your computer and use it in GitHub Desktop.
Replace variables "as words" without replacing the prefixes of other ones.
package main
import (
"fmt"
)
func replaceByRange(s string, startIdx, endIdx int, new string) string {
var res string
var replaced bool
for i := 0; i < len(s); i++ {
if i < startIdx || i >= endIdx {
res += string(s[i])
} else if !replaced {
res += new
replaced = true
}
}
return res
}
func replaceVariables(s, old, new string) string {
if len(old) > len(s) {
return s
}
const varSymbols = "abcdefghijklmnopqrstuvwxyz_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
isVarSymbol := func(r byte) bool {
for _, vs := range varSymbols {
if vs == rune(r) {
return true
}
}
return false
}
var idxs [][2]int
for i := 0; i < len(s); i++ {
if i > len(s)-1 || i+len(old) > len(s) {
break
}
window := s[i : i+len(old)]
if window == old && ((i+len(old) < len(s) && !isVarSymbol(s[i+len(old)])) || i+len(old) == len(s)) {
idxs = append(idxs, [2]int{i, i + len(old)})
}
}
for i := len(idxs) - 1; i >= 0; i-- {
s = replaceByRange(s, idxs[i][0], idxs[i][1], new)
}
return s
}
func main() {
fmt.Println(replaceVariables("var+var1+var2", "var", "rrr"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment