Skip to content

Instantly share code, notes, and snippets.

@tmplinshi
Last active August 31, 2019 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmplinshi/cee1bc644e3fc4e2a4465470d2cd9c4d to your computer and use it in GitHub Desktop.
Save tmplinshi/cee1bc644e3fc4e2a4465470d2cd9c4d to your computer and use it in GitHub Desktop.
; RegExReplaceF(Haystack, NeedleRegEx, FunctionName [, OutputVarCount := "", Limit := -1, StartingPosition := 1])
; Examples
/*
str := "a 100 b 200"
MsgBox % RegExReplaceF(str, "\d+" , "Add8") ; -> "a 108 b 208"
MsgBox % RegExReplaceF(str, "O)(\d+)", "Add5") ; -> "a 105 b 205"
MsgBox % RegExReplaceF(str, "O)(\d+)", Func("AddN").Bind(3)) ; -> "a 103 b 203"
Add8(match) {
return match + 8
}
Add5(match) {
return match.1 + 5
}
AddN(num, match) {
return match.1 + num
}
*/
RegExReplaceF(ByRef Haystack, NeedleRegEx, FunctionName, ByRef OutputVarCount := "", Limit := -1, StartingPosition := 1) {
local out
VarSetCapacity(out, VarSetCapacity(Haystack))
OutputVarCount := 0
while ( pos := RegExMatch(Haystack, NeedleRegEx, match, StartingPosition) )
{
out .= SubStr(Haystack, StartingPosition, pos-StartingPosition)
out .= %FunctionName%(match)
len := IsObject(match) ? match.Len : StrLen(match)
StartingPosition := pos + len
if (++OutputVarCount = Limit)
break
}
return out . SubStr(Haystack, StartingPosition)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment