[英]Regex pattern extract string between curly braces and exclude curly braces
$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 tag end curly braces)The string between \\add[sometext]{
and }
may varies so I can't specify these string in regex pattern I should only consider starting and ending curly braces of \\add[sometext]
我需要提取\\add[sometext]{
和}
之间的字符串(即\\ add标签结尾大括号) \\add[sometext]{
和}
之间的字符串可能会有所不同,因此我无法在正则表达式模式中指定这些字符串只考虑\\add[sometext]
开始和结束花括号
Expected output: 预期产量:
\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 don't know how to get related curly braces (ie \\add tag start { till end }
) 我不知道如何获取相关的花括号(即\\add tag start { till end }
)
You can use a simple regex like this: 您可以使用一个简单的正则表达式,如下所示:
\{([\s\S]*)\}
Match information 比赛信息
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 is 这个正则表达式的思想是
\{([\s\S]*)\}
^--- Capture everything in a greedy way from the first `{` to the last `}`
But also you can do the same thing if you use the s
flag (single line): 但是,如果您使用s
标志(单行),您也可以做同样的事情:
(?s)\{(.*)\} --> using inline `s` flag
\{(.*)\} --> using external `s` flag
For PHP code you can have: 对于PHP代码,您可以:
$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\})\}
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]);
I have got a regex for my requirement. 我有我需要的正则表达式。
$str = preg_replace('/\\\\\\\\add\\s*\\[.*]\\s*{(.*?)\\\\\\\\end{(.[^\\s]*?)}}/s', "$1\\\\end{\\$2}", $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.