RegExReplaceF全部替换函数.ahk

; https://www.autohotkey.com/boards/viewtopic.php?f=76&t=67479

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)
}

 

声明:站内资源为整理优化好的代码上传分享与学习研究,如果是开源代码基本都会标明出处,方便大家扩展学习路径。请不要恶意搬运,破坏站长辛苦整理维护的劳动成果。本站为爱好者分享站点,所有内容不作为商业行为。如若本站上传内容侵犯了原著者的合法权益,请联系我们进行删除下架。