[英]Is there a way to match recursively/nested with regex? (PHP, preg_match_all)
[英]Nested pattern matching with preg_match_all (Regex and PHP)
我正在處理包含特殊標志的文本數據,這些標志的形式為“ {X}”或“ {XX}”,其中X可以是任何字母數字字符。 當這些標志相鄰或分開時,會為其賦予特殊含義。 我需要一個正則表達式,它將匹配相鄰的標志並分隔組中的每個標志。
例如,給定以下輸入:
{B}{R}: Target player loses 1 life.
{W}{G}{U}: Target player gains 5 life.
輸出應為近似值:
("{B}{R}",
"{W}{G}{U}")
("{B}",
"{R}")
("{W}",
"{G}",
"{U}")
我的PHP代碼正確返回了neighbors數組,但是split數組在每個組中僅包含最后一個匹配標志:
$input = '{B}{R}: Target player loses 1 life.
{W}{G}{U}: Target player gains 5 life.';
$pattern = '#((\{[a-zA-Z0-9]{1,2}})+)#';
preg_match_all($pattern, $input, $results);
print_r($results);
輸出:
Array
(
[0] => Array
(
[0] => {B}{R}
[1] => {W}{G}{U}
)
[1] => Array
(
[0] => {B}{R}
[1] => {W}{G}{U}
)
[2] => Array
(
[0] => {R}
[1] => {U}
)
)
謝謝你的幫助!
unset($results[1]);
foreach($results[0] AS $match){
preg_match_all('/\{[a-zA-Z0-9]{1,2}}/', $match, $r);
$results[] = $r[0];
}
這是我知道創建所需數據結構的唯一方法。 不過,preg_split也可以工作:
unset($results[1]);
foreach($results[0] AS $match)
$results[] = preg_split('/(?<=})(?=\{)/', $match);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.