我正在尋找一個正則表達式匹配以下模式:以下文字如何在正則表達式中匹配字符串和重複模式?
--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