#include <MsgBoxConstants.au3> ; to declare the Constants of MsgBox
Local $sRegex = "(?m)^( *)(if(.|\n)+?^(?!\1 |#|\1el|\n))"
Local $sString = "if aaa=1:" & @CRLF & _
"# dfdf fdf" & @CRLF & _
" xxx" & @CRLF & _
" if cc = 4:" & @CRLF & _
" rrr" & @CRLF & _
" else:" & @CRLF & _
" ww" & @CRLF & _
" if aaaaa:" & @CRLF & _
" # dssfdsf" & @CRLF & _
" ttt" & @CRLF & _
"elif bb=2:" & @CRLF & _
"" & @CRLF & _
" if ll is True:" & @CRLF & _
" return" & @CRLF & _
" yyy" & @CRLF & _
"else:" & @CRLF & _
" zzz" & @CRLF & _
"dfsdfsaa"
Local $sSubst = "\1\2\1# endif\n"
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