#include <MsgBoxConstants.au3> ; to declare the Constants of MsgBox
Local $sRegex = "(?xsm) # free-spacing mode, multi-line" & @CRLF & _
"(?=.*?pig) # lookahead: if pig is not there, fail right away to save the effort" & @CRLF & _
"(?: # start counter-line-skipper (lines that don't include pig)" & @CRLF & _
" (?: # skip one line that doesn't have pig" & @CRLF & _
" ^ # beginning of line" & @CRLF & _
" (?:(?!pig)[^\r\n])* # zero or more chars not followed by pig" & @CRLF & _
" (?:\r?\n) # newline chars" & @CRLF & _
" ) " & @CRLF & _
" # for each line skipped, let Group 1 match an ever increasing portion of the numbers string at the bottom" & @CRLF & _
" (?= # lookahead" & @CRLF & _
" [^:]+ # skip all chars that are not colons" & @CRLF & _
" ( # start Group 1" & @CRLF & _
" (?(1)\1) # if Group 1 is set, match Group 1" & @CRLF & _
" # (?>\1?) # alternate phrasing for the above" & @CRLF & _
" :\d+ # match a colon and some digits" & @CRLF & _
" ) # end Group 1" & @CRLF & _
" ) # end lookahead" & @CRLF & _
")*+ # end counter-line-skipper: zero or more times" & @CRLF & _
".*? # match" & @CRLF & _
"\K # drop everything we've matched so far" & @CRLF & _
"pig # match pig (this is the match!)" & @CRLF & _
"(?=[^:]+(?(1)\1):(\d+)) # capture the next number to Group 2"
Local $sString = "my cat pi g" & @CRLF & _
"dog pi g" & @CRLF & _
"my pig" & @CRLF & _
"my cow" & @CRLF & _
"my mouse" & @CRLF & _
"" & @CRLF & _
":1:2:3:4:5:6:7"
Local $sSubst = "\2"
Local $sResult = StringRegExpReplace($sString, $sRegex, $sSubst)
MsgBox($MB_SYSTEMMODAL, "Result", $sResult)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for AutoIt, please visit: https://www.autoitscript.com/autoit3/docs/functions/StringRegExp.htm