在嵌套括号内提取字符串

lor*_*llo 6 python algorithm brackets

我需要从嵌套括号中提取字符串,如下所示:

[ this is [ hello [ who ] [what ] from the other side ] slim shady ]
Run Code Online (Sandbox Code Playgroud)

结果(订单无关紧要):

This is slim shady
Hello from the other side
Who 
What
Run Code Online (Sandbox Code Playgroud)

注意,字符串可以有N个括号,它们将始终有效,但可能嵌套也可能不嵌套.此外,字符串不必以括号开头.

我在网上找到类似问题的解决方案表明正则表达式,但我不确定它会在这种情况下起作用.

我正在考虑实现这类似于我们如何检查字符串是否具有所有有效括号:

穿过绳子.如果我们看到[我们在堆栈上推送它的索引,如果我们看到一个],我们从那里子串到当前点.

但是,我们需要从原始字符串中删除该子字符串,因此我们不会将其作为任何输出的一部分.所以,我没有推动只是将索引推入堆栈,而是在考虑创建一个LinkedList,当我们找到[我们在LinkedList上插入该Node时].这将允许我们从LinkedList中轻松删除子字符串.

这是一个好方法还是有一个更清洁,已知的解决方案?

编辑:

'[ this is [ hello [ who ] [what ] from the other [side] ] slim shady ][oh my [g[a[w[d]]]]]'
Run Code Online (Sandbox Code Playgroud)

应该退货(订单无关紧要):

this is slim shady
hello from the other
who 
what 
side
oh my
g
a
w
d
Run Code Online (Sandbox Code Playgroud)

白色空间并不重要,之后删除是微不足道的.重要的是能够区分括号内的不同内容.通过在新行中分隔它们,或者有一个字符串列表.

Ara*_*Fey 5

使用正则表达式可以很容易地解决这个问题:

import re

s= '[ this is [ hello [ who ] [what ] from the other [side] ] slim shady ][oh my [g[a[w[d]]]]]'

result= []
pattern= r'\[([^[\]]*)\]' #regex pattern to find non-nested square brackets
while '[' in s: #while brackets remain
    result.extend(re.findall(pattern, s)) #find them all and add them to the list
    s= re.sub(pattern, '', s) #then remove them
result= filter(None, (t.strip() for t in result)) #strip whitespace and drop empty strings

#result: ['who', 'what', 'side', 'd', 'hello   from the other', 'w', 'this is  slim shady', 'a', 'g', 'oh my']
Run Code Online (Sandbox Code Playgroud)


Niz*_*med 5

此代码按字符扫描文本,并list在每个打开时将空白打开到堆栈,[并在list每次关闭时弹出从堆栈中推送的最后一个].

text = '[ this is [ hello [ who ] [what ] from the other side ] slim shady ]'

def parse(text):
    stack = []
    for char in text:
        if char == '[':
            #stack push
            stack.append([])
        elif char == ']':
            yield ''.join(stack.pop())
        else:
            #stack peek
            stack[-1].append(char)

print(tuple(parse(text)))
Run Code Online (Sandbox Code Playgroud)

输出;

(' who ', 'what ', ' hello   from the other side ', ' this is  slim shady ')
(' who ', 'what ', 'side', ' hello   from the other  ', ' this is  slim shady ', 'd', 'w', 'a', 'g', 'oh my ')
Run Code Online (Sandbox Code Playgroud)