From c5fb20e96a4e9ec56b63efdb316d0968779093d7 Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Wed, 26 Mar 2025 12:27:40 +0100 Subject: [PATCH] Implement named capture groups --- processor/regex.go | 48 +++++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/processor/regex.go b/processor/regex.go index 40cf861..3abdec5 100644 --- a/processor/regex.go +++ b/processor/regex.go @@ -145,31 +145,42 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr continue } - namedCaptures := make(map[string]string) - groupNames := compiledPattern.SubexpNames() - - for i, name := range groupNames { - if i == 0 { - continue - } - if i < len(match) { - namedCaptures[name] = string(match[i]) - } - } - log.Printf("Named captures: %v", namedCaptures) - captures := make([]string, 0, len(groups)/2) for j := 0; j < len(groups); j += 2 { captures = append(captures, content[groups[j]:groups[j+1]]) } log.Printf("Captured groups: %v", captures) + namedCaptures := make(map[string]string) + namedCaptureGroups := make(map[string][2]int) + groupNames := compiledPattern.SubexpNames()[1:] + for i, name := range groupNames { + if name == "" { + continue + } + namedCaptures[name] = captures[i] + namedCaptureGroups[name] = [2]int{groups[i*2], groups[i*2+1]} + } + + log.Printf("Named captures: %v", namedCaptures) + if err := p.ToLua(L, captures); err != nil { log.Printf("Error setting Lua variables: %v", err) continue } log.Println("Lua variables set successfully") + for name, capture := range namedCaptures { + if name == "" { + continue + } + if val, err := strconv.ParseFloat(capture, 64); err == nil { + L.SetGlobal(name, lua.LNumber(val)) + } else { + L.SetGlobal(name, lua.LString(capture)) + } + } + if err := L.DoString(luaExpr); err != nil { log.Printf("Error executing Lua code %s for group %s: %v", luaExpr, captures, err) continue @@ -202,6 +213,17 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr replacement = replacement[:groupStart] + newVal + replacement[groupEnd:] } + for i := len(namedCaptures) - 1; i >= 0; i-- { + name := groupNames[i] + if name == "" { + continue + } + groupStart := namedCaptureGroups[name][0] - matchIndices[0] + groupEnd := namedCaptureGroups[name][1] - matchIndices[0] + luaValue := L.GetGlobal(name).String() + replacement = replacement[:groupStart] + luaValue + replacement[groupEnd:] + } + modificationCount++ result = result[:matchIndices[0]] + replacement + result[matchIndices[1]:] log.Printf("Modification count updated: %d", modificationCount)