[英]How do I match nested braces using regular expressions in PHP?
我有一個我想要匹配的LaTeX文檔。 我需要一個符合以下條件的RegEx匹配:
\ # the backslash in the beginning
[a-zA-Z]+ #a word
(\{.+\})* # any amount of {something}
然而,她是抓住了;
在最后一行中,它需要貪婪,並且2.需要在其內部具有匹配的數量{}
。
這意味着如果我有字符串\\test{something\\somthing{9}}
它將匹配整個。 它需要按順序( {}
)。 因此它與以下內容不匹配:
\\ LaTeX {}是\\ TeX {}的文檔准備系統
只是
\\膠乳{}
和
\\ 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 ,因為它支持遞歸正則表達式匹配。 但是 ,正如我所說的,如果你的類似LaTeX的字符串中有注釋可以包含{
或}
,那么這將失敗。
演示:
$text = 'This is a \LaTeX{ foo { bar { ... } baz test {} done } } document
preparation system for the \TeX{a{b{c}d}e{f}g{h}i}-y people out there';
preg_match_all('/\\\\[A-Za-z]+(\{(?:[^{}]|(?1))*})/', $text, $matches, PREG_SET_ORDER);
print_r($matches);
產生:
Array
(
[0] => Array
(
[0] => \LaTeX{ foo { bar { ... } baz test {} done } }
[1] => { foo { bar { ... } baz test {} done } }
)
[1] => Array
(
[0] => \TeX{a{b{c}d}e{f}g{h}i}
[1] => {a{b{c}d}e{f}g{h}i}
)
)
快速解釋:
\\\\ # the literal '\'
[A-Za-z]+ # one or more letters
( # start capture group 1 <-----------------+
\{ # the literal '{' |
(?: # start non-capture group A |
[^{}] # any character other than '{' and '}' |
| # OR |
(?1) # recursively match capture group 1 ---+
) # end non-capture group A
* # non-capture group A zero or more times
} # the literal '}'
) # end capture group 1
不幸的是,我認為這是不可能的。 支架匹配(檢測正確配對的嵌套括號)通常用作有限狀態機無法解決的問題的示例,例如正則表達式解析器。 您可以使用無上下文語法來完成它,但這不是正則表達式的工作原理。 您最好的解決方案是使用正則表達式{*[^{}]*}*
進行初始檢查,然后使用另一個短腳本來檢查它是否為偶數。
總之:不要只用正則表達式來做。 這不是單獨用正則表達式解決的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.