我正在寻找一个正则表达式匹配以下模式:以下文字如何在正则表达式中匹配字符串和重复模式?
--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 1
和answer 1
例如代码: https://regex101.com/r/59OKzs/1
你也应该与空白 - [' - - *(-pre-(*) - ?\ /预\ S *)?+'](https://regex101.com/r/HVCngE/2)。但是,如果您想要获得每个组的捕获量,请不要量化捕获组。使用[' - (。*?) - 。*? - pre - (。*?) - \/pre \ s * -pre - (。*?) - \/pre-'](https:/ /regex101.com/r/HVCngE/3)。 –
第二个捕获组之前的'。*?'在每种情况下“吞噬”了第一个前块。 – CBroe
@WiktorStribiżew谢谢你,这项工作,如果我只有2条评论和2个答案,如果评论的数量不固定为2 – karim