Add replaceCommands to avoid index suicide
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -71,6 +72,11 @@ type NamedCapture struct {
|
||||
Value string
|
||||
Range [2]int
|
||||
}
|
||||
type ReplaceCommand struct {
|
||||
From int
|
||||
To int
|
||||
With string
|
||||
}
|
||||
|
||||
// ProcessContent applies regex replacement with Lua processing
|
||||
func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr string) (string, int, int, error) {
|
||||
@@ -249,6 +255,7 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr
|
||||
replacement = replacementVar.String()
|
||||
}
|
||||
if replacement == "" {
|
||||
commands := make([]ReplaceCommand, 0, len(modsMap))
|
||||
// Apply the modifications to the original match
|
||||
replacement = match
|
||||
for i := len(modsMap) - 1; i >= 0; i-- {
|
||||
@@ -258,7 +265,14 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr
|
||||
// To relate them to match we have to subtract the match start index
|
||||
groupStart := groups[i*2] - matchIndices[0]
|
||||
groupEnd := groups[i*2+1] - matchIndices[0]
|
||||
replacement = replacement[:groupStart] + newVal + replacement[groupEnd:]
|
||||
// replacement = replacement[:groupStart] + newVal + replacement[groupEnd:]
|
||||
log.Printf("%#v", groupStart)
|
||||
log.Printf("%#v", groupEnd)
|
||||
// commands = append(commands, ReplaceCommand{
|
||||
// From: groupStart,
|
||||
// To: groupEnd,
|
||||
// With: newVal,
|
||||
// })
|
||||
}
|
||||
|
||||
for i := len(namedCaptures) - 1; i >= 0; i-- {
|
||||
@@ -269,7 +283,20 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr
|
||||
groupStart := capture.Range[0] - matchIndices[0]
|
||||
groupEnd := capture.Range[1] - matchIndices[0]
|
||||
luaValue := L.GetGlobal(capture.Name).String()
|
||||
replacement = replacement[:groupStart] + luaValue + replacement[groupEnd:]
|
||||
// replacement = replacement[:groupStart] + luaValue + replacement[groupEnd:]
|
||||
commands = append(commands, ReplaceCommand{
|
||||
From: groupStart,
|
||||
To: groupEnd,
|
||||
With: luaValue,
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(commands, func(i, j int) bool {
|
||||
return commands[i].From > commands[j].From
|
||||
})
|
||||
|
||||
for _, command := range commands {
|
||||
replacement = replacement[:command.From] + command.With + replacement[command.To:]
|
||||
}
|
||||
}
|
||||
modificationCount++
|
||||
|
Reference in New Issue
Block a user