Regex pattern highlight string between curly braces and curly brace exclusion

$str='\add[sometext]{\begin{equation}\label{eqn:3}
f_{1} =
\begin{cases}}
\beta_{1} + \beta_{2}f_{2} & f_{2}\leq \gamma\\
\beta_{1} + \beta_{2}\gamma + \beta_{4}(f_{2}-\gamma) & f_{2} >\gamma
\end{cases}sdsdssd,
\end{equation}}
 it may have some extra code here with {}
 \end{equation}}'

      

I need to extract the string between \add[sometext]{

and }

(ietill \ add the end of the end of the curly braces). The line between \add[sometext]{

and }

can vary, so I cannot specify this line in the regex pattern I have to consider only the beginning and ending of curly braces\add[sometext]

Expected Result:

\begin{equation}\label{eqn:3}
    f_{1} =
    \begin{cases}
    \beta_{1} + \beta_{2}f_{2} & f_{2}\leq \gamma\\
    \beta_{1} + \beta_{2}\gamma + \beta_{4}(f_{2}-\gamma) & f_{2} >\gamma
    \end{cases}sdsdssd,
    \end{equation}

      

I tried:

$str=preg_replace('/\\\\add\s*\[\s*\w*\]\s*{(.*?)}/s,$1,$match)

I have no idea how to get the associated curly braces (i.e. \add tag start { till end }

)

0


source to share


3 answers


I have a regex for my requirement.

$str = preg_replace('/\\\\add\s*\[.*]\s*{(.*?)\\\\end{(.[^\s]*?)}}/s', "$1\\end{\$2}", $str);



Working demo

0


source


You can use a simple regex:

\{([\s\S]*)\}

      

Regular expression visualization

Working demo

enter image description here

Match info

MATCH 1
1.  [21-226]    `\begin{equation}\label{eqn:3}
f_{1} =
\begin{cases}}
\beta_{1} + \beta_{2}f_{2} & f_{2}\leq \gamma\\
\beta_{1} + \beta_{2}\gamma + \beta_{4}(f_{2}-\gamma) & f_{2} >\gamma
\end{cases}sdsdssd,
\end{equation}`

      

As you can see in the match information, the captured content is what you need.

The idea behind this regex



\{([\s\S]*)\}
      ^--- Capture everything in a greedy way from the first `{` to the last `}`

      

But you can do the same if you use a flag s

(one line):

(?s)\{(.*)\} --> using inline `s` flag
    \{(.*)\} --> using external `s` flag

      

For PHP code, you can:

$re = "@\\{(.*)\\}@s"; 
$str = "\$str='\add[sometext]{\begin{equation}\label{eqn:3}\nf_{1} =\n\begin{cases}}\n\beta_{1} + \beta_{2}f_{2} & f_{2}\leq \gamma\\\n\beta_{1} + \beta_{2}\gamma + \beta_{4}(f_{2}-\gamma) & f_{2} >\gamma\n\end{cases}sdsdssd,\n\end{equation}}'"; 

preg_match($re, $str, $matches);

      

Update:

You can use this regex for your updated comments in the question:

\{([\s\S]*equation\})\}

      

Working demo

+1


source


how about this:

$str='\add[sometext]{\begin{equation}\label{eqn:3}
f_{1} =
\begin{cases}
\beta_{1} + \beta_{2}f_{2} & f_{2}\leq \gamma\\
\beta_{1} + \beta_{2}\gamma + \beta_{4}(f_{2}-\gamma) & f_{2} >\gamma
\end{cases}sdsdssd,
\end{equation}}';

$str= preg_match('/\\\\add\s*\[\s*\w*\]\s*{(.*?)}$/s',$str,$match);

var_dump($match[1]);

      

+1


source







All Articles