Wrote function and example for ReplaceAllLiteral()
This commit is contained in:
@@ -162,3 +162,11 @@ func ExampleReg_ReplaceAll() {
|
||||
fmt.Println(regexComp.ReplaceAll(inputStr, `$2$1`))
|
||||
// Output: d5t9
|
||||
}
|
||||
|
||||
func ExampleReg_ReplaceAllLiteral() {
|
||||
regexStr := `fox|dog`
|
||||
inputStr := "the quick brown fox jumped over the lazy dog"
|
||||
regexComp := regex.MustCompile(regexStr)
|
||||
fmt.Println(regexComp.ReplaceAll(inputStr, `duck`))
|
||||
// Output: the quick brown duck jumped over the lazy duck
|
||||
}
|
||||
|
@@ -404,7 +404,7 @@ func (re Reg) ReplaceAll(src string, repl string) string {
|
||||
currentMatch := 0
|
||||
dst := ""
|
||||
for i < len(src) {
|
||||
if currentMatch <= len(matches) && matches[currentMatch][0].IsValid() && i == matches[currentMatch][0].StartIdx {
|
||||
if currentMatch < len(matches) && matches[currentMatch][0].IsValid() && i == matches[currentMatch][0].StartIdx {
|
||||
dst += re.Expand("", repl, src, matches[currentMatch])
|
||||
i = matches[currentMatch][0].EndIdx
|
||||
currentMatch++
|
||||
@@ -415,3 +415,23 @@ func (re Reg) ReplaceAll(src string, repl string) string {
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// ReplaceAllLiteral replaces all matches of the expression in src, with the text in repl. The text is replaced directly,
|
||||
// without any expansion.
|
||||
func (re Reg) ReplaceAllLiteral(src string, repl string) string {
|
||||
zerogroups := re.FindAll(src)
|
||||
currentMatch := 0
|
||||
i := 0
|
||||
dst := ""
|
||||
|
||||
for i < len(src) {
|
||||
if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx {
|
||||
dst += repl
|
||||
i = zerogroups[currentMatch].EndIdx
|
||||
} else {
|
||||
dst += string(src[i])
|
||||
i++
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
Reference in New Issue
Block a user