2017-03-16 40 views
1

我正在尋找一個正則表達式匹配以下模式:以下文字如何在正則表達式中匹配字符串和重複模式?

--comment-- 
list of comments 
-pre- 
comment 1 
-/pre- 

-pre- 
comment 2 
-/pre- 

--Answers-- 
list of Answers 
-pre- 
Answer 1 
-/pre- 

-pre- 
Answer 2 
-/pre- 

應返回:任何文本-/pre--pre-任何文本-/pre-

例如

--header--任何文本-pre-如下圖應用正則表達式:

Array 
(
    [comments] => Array 
     (
      [0] => comment 1 
      [1] => comment 2 
     ) 

    [answers] => Array 
     (
      [0] => answer 1 
      [1] => answer 2 
     ) 

) 

我嘗試以下正則表達式--(.*?)--.*?(-pre-(.*?)-\/pre-)+但它只能匹配comment 1answer 1

例如代碼: https://regex101.com/r/59OKzs/1

+0

你也應該與空白 - [' - - *(-pre-(*) - ?\ /預\ S *)?+'](https://regex101.com/r/HVCngE/2)。但是,如果您想要獲得每個組的捕獲量,請不要量化捕獲組。使用[' - (。*?) - 。*? - pre - (。*?) - \/pre \ s * -pre - (。*?) - \/pre-'](https:/ /regex101.com/r/HVCngE/3)。 –

+0

第二個捕獲組之前的'。*?'在每種情況下「吞噬」了第一個前塊。 – CBroe

+0

@WiktorStribiżew謝謝你,這項工作,如果我只有2條評論和2個答案,如果評論的數量不固定爲2 – karim

回答

0

正則表達式:

(?:--([^-]+)--(?:(?!-pre-).)+|(?!\A)\G)\s*-pre-\s*((?:(?!-/pre-).)*)-/pre-\K 

Live demo

PHP:

preg_match_all('~(?:--([^-]+)--(?:(?!-pre-).)+|(?!\A)\G)\s*-pre-\s*((?:(?!-/pre-).)*)-/pre-\K~s', $str, $matches, PREG_SET_ORDER); 

要整合相應的鍵和值:(。*?) -

// Filter empty values 
$matches = array_map(function($v) { 
    return array_values(array_filter($v)); 
}, $matches); 

// Initialize two variables which we use them soon 
$index = null; $finalArray = []; 

// Iterate over recent matches in order to apply keys 
array_map(function($array) use (&$index, &$finalArray) { 
    count($array) == 2 ? ($index = $array[0]) && ($finalArray[$index][] = $array[1]) : $finalArray[$index][] = $array[0]; 
}, $matches); 

// Print out 
print_r($finalArray); 

PHP live demo

0

也許使用preg_match_all/--(.*?)--.*?-pre-\n*(.*?)\n*-\/pre-.*?-pre-\n*(.*?)\n*-\/pre-/s

preg_match_all('/--(.*?)--.*?-pre-\n*(.*?)\n*-\/pre-.*?-pre-\n*(.*?)\n*-\/pre-/s',$string,$matches, PREG_SET_ORDER); 

for($i=0;$i<count($matches);$i++) 
    $output[$matches[$i][1]] = array($matches[$i][2], $matches[$i][3]); 

print_r($output);