我需要像这样从嵌套括号中提取字符串:
[ this is [ hello [ who ] [what ] from the other side ] slim shady ]
结果(顺序无关紧要):
This is slim shady
Hello from the other side
Who
What
请注意,该字符串可以有N个括号,并且它们始终有效,但可以嵌套或可以不嵌套。另外,字符串不必以方括号开头。
我在网上找到的针对类似问题的解决方案建议使用正则表达式,但是我不确定在这种情况下是否可以使用正则表达式。
我正在考虑实现类似于我们检查字符串是否具有所有有效括号的方法:
遍历字符串。如果我们看到[我们将其索引压入堆栈,如果我们看到],则从那里子串到当前位置。
但是,我们需要从原始字符串中删除该子字符串,以免将其作为任何输出的一部分。因此,我在考虑创建一个LinkedList而不是仅仅将索引推送到堆栈中,并且当我们找到一个[时,我们将该Node插入LinkedList上。这将使我们能够轻松地从LinkedList中删除子字符串。
这是一个好方法还是有一个更清洁,已知的解决方案?
编辑:
'[ this is [ hello [ who ] [what ] from the other [side] ] slim shady ][oh my [g[a[w[d]]]]]'
应该退货(顺序无关紧要):
this is slim shady
hello from the other
who
what
side
oh my
g
a
w
d
空白无所谓,事后将其删除很简单。重要的是能够区分方括号内的不同内容。通过用换行符将它们分开,或具有字符串列表。
此代码按字符扫描文本,并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)))
输出;
(' 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 ')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句