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中文网其他相关文章!