gpt4 book ai didi

php - 如何在 PHP 中使用正则表达式匹配嵌套的大括号?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:49 24 4
gpt4 key购买 nike

我有一个要匹配的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com