From 7f4392b10e184470e365e3b83a02fa864fb00525 Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Wed, 26 Mar 2025 12:58:51 +0100 Subject: [PATCH] Implement "replacement" variable that simply replaces the match --- processor/regex.go | 46 +++++++++++++++++++++++------------------ processor/regex_test.go | 6 +++--- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/processor/regex.go b/processor/regex.go index 767f2b7..ac1e72b 100644 --- a/processor/regex.go +++ b/processor/regex.go @@ -213,29 +213,35 @@ func (p *RegexProcessor) ProcessContent(content string, pattern string, luaExpr continue } - // Apply the modifications to the original match - replacement := match - for i := len(modsMap) - 1; i >= 0; i-- { - newVal := modsMap[i] - log.Printf("Applying modification: %s", newVal) - // Indices of the group are relative to content - // 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 := "" + replacementVar := L.GetGlobal("replacement") + if replacementVar.Type() != lua.LTNil { + replacement = replacementVar.String() } - - for i := len(namedCaptures) - 1; i >= 0; i-- { - capture := namedCaptures[i] - if capture.Name == "" { - continue + if replacement == "" { + // Apply the modifications to the original match + replacement = match + for i := len(modsMap) - 1; i >= 0; i-- { + newVal := modsMap[i] + log.Printf("Applying modification: %s", newVal) + // Indices of the group are relative to content + // 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:] } - groupStart := capture.Range[0] - matchIndices[0] - groupEnd := capture.Range[1] - matchIndices[0] - luaValue := L.GetGlobal(capture.Name).String() - replacement = replacement[:groupStart] + luaValue + replacement[groupEnd:] - } + for i := len(namedCaptures) - 1; i >= 0; i-- { + capture := namedCaptures[i] + if capture.Name == "" { + continue + } + groupStart := capture.Range[0] - matchIndices[0] + groupEnd := capture.Range[1] - matchIndices[0] + luaValue := L.GetGlobal(capture.Name).String() + replacement = replacement[:groupStart] + luaValue + replacement[groupEnd:] + } + } modificationCount++ result = result[:matchIndices[0]] + replacement + result[matchIndices[1]:] log.Printf("Modification count updated: %d", modificationCount) diff --git a/processor/regex_test.go b/processor/regex_test.go index 53f7444..4f5cb50 100644 --- a/processor/regex_test.go +++ b/processor/regex_test.go @@ -871,7 +871,7 @@ func TestLuaFunctionsOnNamedCaptures(t *testing.T) { `', - price, qty, price * qty)`) + price, qty, price * qty)`) if err != nil { t.Fatalf("Error processing content: %v", err)