php小編香蕉將為大家介紹一種在PHP中提取帶有嵌套括號的字串中的值的方法。在開發過程中,有時我們會遇到需要從一個複雜的字串中提取特定值的情況,而這些值可能被嵌套在多個括號中。本文將向您展示如何使用PHP的字串處理函數,透過遞歸和正規表示式來解決這個問題。無論您是初學者還是有經驗的開發者,這篇文章都將為您提供實用的技巧和範例程式碼,幫助您輕鬆應對這類任務。
給定一個輸入字串,例如:
AB[C[DA,BF,GAL],DB[NX,AQQ,AAN,B],F[H[GG,BAND]]]
傳回字串陣列:
["ABCDA", "ABCBF", "ABCGAL", "ABDBNX", "ABDBAQQ", "ABDBAAN", "ABDBB", "ABFHGG"]
我能夠編寫部分解決方案,但如果有多個 [children]
,則很難追蹤父節點。
另一個測試字串:ZHLADAOR[R[G[45D[COI,EMA],Q5D[COI,EMA],U5D[COI,EMA],Y5D[COI,EMA]],HE5D[COI ,EMA]], SG[A5D[COI,EMA],E5D[COI,EMA],I5D[COI,EMA]]]
<code>func expandNestedString(str string) []string { var parts []string var currentPart []rune var openBrackets int var level int var bitsBeforeComma int var prevBitsBeforeComma int for _, char := range str { if char == '[' { openBrackets++ level++ prevBitsBeforeComma = bitsBeforeComma bitsBeforeComma = 0 } else if char == ']' { openBrackets-- if openBrackets == 0 { if level == 0 && len(currentPart) > 0 { parts = append(parts, string(currentPart)) } currentPart = []rune{} level-- } else { parts = append(parts, string(currentPart)) currentPart = currentPart[:len(currentPart)-(bitsBeforeComma+prevBitsBeforeComma)] bitsBeforeComma = 0 } } else if char == ',' { parts = append(parts, string(currentPart)) currentPart = currentPart[:len(currentPart)-bitsBeforeComma] bitsBeforeComma = 0 } else { currentPart = append(currentPart, char) bitsBeforeComma++ } } if len(currentPart) > 0 { parts = append(parts, string(currentPart)) } return parts } </code>
通常,這些似乎需要平衡括號或追蹤先前字元模式的問題可以透過遞歸很好地解決。這是一個有效的解決方案
func expand(s []rune, idx int) ([][]rune, int) { var prefix []rune var result [][]rune for ; idx < len(s); idx++ { switch s[idx] { case '[': runes, lastIdx := expand(s, idx+1) for _, r := range runes { result = append(result, append(prefix, r...)) } idx = lastIdx prefix = []rune{} case ']': if len(prefix) > 0 { result = append(result, prefix) } return result, idx case ',': if len(prefix) > 0 { result = append(result, prefix) prefix = []rune{} } default: prefix = append(prefix, s[idx]) } } if len(prefix) > 0 { result = append(result, prefix) } return result, idx } func expandNestedString(s string) []string { runes, _ := expand([]rune(s), 0) var result []string for _, r := range runes { result = append(result, string(r)) } return result }
以上是從帶有嵌套括號的字串中提取值的詳細內容。更多資訊請關注PHP中文網其他相關文章!