2017-03-16 32 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);