在沒有遞歸或平衡組的情況下匹配嵌套括號
挑戰:
挑戰:(F(i(r(s)t))) ((S)(e)((c)(o))(n)d) (((((((Third)))))))
挑戰:
(?=\()(?:(?=.*?\((?!.*?)(.*\)(?!.*).*))(?=.*?\)(?!.*?)(.*)).)+?.*?(?=)[^(]*(?=$)挑戰:
挑戰:
分解:
檢查'(': 繼續遍歷字串,直到遇到'('。
匹配平衡括號:(?=\()(?=((?:(?=.*?\((?!.*?)(.*\)(?!.*).*))(?=.*?\)(?!.*?)(.*)).)+?.*?(?=)[^(]*(?=$)))使用兩個前瞻來確保下一個'('和')'以平衡的方式匹配,捕獲內部內容。結束括號檢查:
檢查與先前匹配的'(' 匹配的結束')' 並進一步前進。 (' )' 的外部群組。匹配的內容保存在一對平衡的括號內:
全面破壞:
表格總結了正規表示式的組件和功能:Note | Component | Description |
---|---|---|
(?=() | Look for '(' | |
(?: | Start group for iteration | |
(?=.?((?!.?1)) | Look for '(' not followed by 1, which contains the matched inner content | |
(.)(?!.2).*)) | Capture inner content and check for at least one more ')' | |
(?=.?)(?!.?3)) | Look for ')' not followed by 2, which contains the matched outer content | |
(. ) | Capture outer content | |
. | Consume a character | |
) | Close group | |
? | Match as few times as possible | |
.*?(?=1) | Match up to and including the last '(' | |
1*(?=2$) | Match up to the last ')' without encountering more '(' |
以上是如何在沒有遞歸或平衡組的情況下匹配嵌套括號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!