#include <MsgBoxConstants.au3> ; to declare the Constants of MsgBox
Local $sRegex = "\\caption(?:of)?+\b(?:\[[^][]*\])?+\s*+(?!(\{(?:[^}{]++|(?-1))*+\}))"
Local $sString = " \begin{figure} " & @CRLF & _
" \includegraphics{pic.pdf}" & @CRLF & _
" \caption[]{My caption \\ " & @CRLF & _
" Source: XYZ" & @CRLF & _
" \label{fig:pic_1} " & @CRLF & _
" \end{figure}" & @CRLF & _
" " & @CRLF & _
" " & @CRLF & _
" \begin{figure}[H]" & @CRLF & _
" \includegraphics{pic.pdf}" & @CRLF & _
" \captionof[]{My caption \\ xyz \\ abc" & @CRLF & _
" \label{fig:pic_1} }" & @CRLF & _
" \end{figure}" & @CRLF & _
" " & @CRLF & _
" " & @CRLF & _
" \begin{figure}[H]" & @CRLF & _
" \includegraphics{pic.pdf}" & @CRLF & _
" \caption[]{My caption {with extra brackets}" & @CRLF & _
" Source: XYZ}" & @CRLF & _
" \label{fig:pic_1} " & @CRLF & _
" \end{figure}" & @CRLF & _
" " & @CRLF & _
" \begin{figure}[H]" & @CRLF & _
" \includegraphics{pic.pdf}" & @CRLF & _
" \caption[]{My caption}" & @CRLF & _
" \end{figure}" & @CRLF & _
" " & @CRLF & _
" Some text\\ %% This \\ should not be changed, it's not within a caption" & @CRLF & _
" More text" & @CRLF & _
" " & @CRLF & _
" \begin{figure}[H]" & @CRLF & _
" \includegraphics{pic.pdf}" & @CRLF & _
" \caption[]{My caption \\ Source: XYZ}" & @CRLF & _
" \label{fig:pic_1} " & @CRLF & _
" \end{figure}"
Local $sSubst = "\\par"
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