首頁  >  文章  >  Java  >  嵌套括號可以在沒有遞歸或平衡組的情況下匹配嗎?

嵌套括號可以在沒有遞歸或平衡組的情況下匹配嗎?

Patricia Arquette
Patricia Arquette原創
2024-10-24 12:25:02956瀏覽

Can Nested Brackets Be Matched Without Recursion or Balancing Groups?

在沒有遞歸或平衡組的情況下匹配嵌套括號

使用正則表達式匹配括號可能具有挑戰性,嵌套特別是在像Java 這樣的語言中,遞歸且不支援平衡組。幸運的是,使用前向引用確實可以克服此限制。

匹配外部群組

以下正規表示式[1] 符合外部群組括號而不對深度施加限制:

這裡,表達式向前查找左括號,排除不匹配的左括號,並捕獲相應的右括號。捕獲的子字串雖然無用,但可以作為佔位符來完成匹配。

匹配內部組

要包含內部組,我們可以捕捉以下表達式 [2]:

[2]

:

透過新增擷取群組並調整反向引用索引,此表達式也會擷取內部群組。

工作原理

Component Description
(?=() Asserts that '(' precedes complex parsing
(?: Start of non-capturing group for repeated string processing
(?= Assert that the next '(' follows
.?((?!.?1) Match until the next '(' not followed by group 1
(.)(?!.2).* Fill group 1 with the string, ensuring another ')' exists
) Assert that the matching ')' is valid
.?)(?!.?2) Assert that the next ')' not followed by group 2 exists
(.*) Fill group 2 with the remaining string
) Assert that the matching ')' is valid
Consume a single character to continue matching within the group
) ? Repeat the group (in the inner loop)
.*?(?=1) Match up to and including the last '(' found
1*(?=2$) Match up to the last ')' (but within the valid group)
該方法迭代字串,匹配下一個左括號和右括號,同時捕獲每種情況下的剩餘字串。前瞻確保括號以平衡方式匹配。 表達式構造如下:

此方法可以有效率地匹配巢狀括號,無需遞歸或平衡組。


  1. (

以上是嵌套括號可以在沒有遞歸或平衡組的情況下匹配嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn