我有一个要匹配的 LaTeX 文档。我需要匹配以下内容的 RegEx 匹配项:
\ # the backslash in the beginning
[a-zA-Z]+ #a word
(\{.+\})* # any amount of {something}
不过,她是抓到的;
在最后一行中,它 1. 需要贪婪,并且 2. 需要在其内部具有匹配数量的 {}
。
意味着如果我有字符串 \test{something\somthing{9}}
它会匹配整体。它需要按此顺序 ({}
)。所以它不符合以下内容:
\LaTeX{} is a document preparation system for the \TeX{}
只是
\LaTeX{}
和
\TeX{}
帮助任何人?也许有人对匹配有更好的想法?我不应该使用正则表达式吗?
最佳答案
这可以通过递归来完成:
$input = "\LaTeX{} is a document preparation system for the \TeX{}
\latex{something\somthing{9}}";
preg_match_all('~(?<token>
\\\\ # the slash in the beginning
[a-zA-Z]+ #a word
(\{[^{}]*((?P>token)[^{}]*)?\}) # {something}
)~x', $input, $matches);
这正确匹配 \LaTeX{}
、\TeX{}
和 \latex{something\somthing{9}}
关于php - 如何在 PHP 中使用正则表达式匹配嵌套的大括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4759029/