Home  >  Article  >  Backend Development  >  Extract value from string with nested brackets

Extract value from string with nested brackets

WBOY
WBOYforward
2024-02-08 23:54:10736browse

Extract value from string with nested brackets

php editor Banana will introduce you to a method to extract the value from a string with nested brackets in PHP. During development, sometimes we encounter situations where we need to extract specific values ​​from a complex string, and these values ​​may be nested in multiple parentheses. This article will show you how to use PHP's string processing functions, recursion and regular expressions to solve this problem. Whether you are a beginner or an experienced developer, this article will provide you with practical tips and sample code to help you tackle this type of task with ease.

Question content


Given an input string, for example:

AB[C[DA,BF,GAL],DB[NX,AQQ,AAN,B],F[H[GG,BAND]]]

Return string array:

["ABCDA", "ABCBF", "ABCGAL", "ABDBNX", "ABDBAQQ", "ABDBAAN", "ABDBB", "ABFHGG"]

I was able to write a partial solution, but if there are multiple [children] it becomes difficult to keep track of the parent node.

Another test string: 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>



Solution


Often these problems that seem to require balancing parentheses or keeping track of previous character patterns can be solved nicely with recursion. This is a valid solution

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
}

Demo

The above is the detailed content of Extract value from string with nested brackets. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete