下面的表达式可以很好地提取data
字符串中以单词Block
开头、后接左括号{
并以右括号'}'结尾的部分:
data ="""
Somewhere over the rainbow
Way up high
Block {
line 1
line 2
line 3
}
And the dreams that you dreamed of
Once in a lullaby
"""
regex = re.compile("""(Block\ {\n\ [^\{\}]*\n}\n)""", re.MULTILINE)
result = regex.findall(data)
print result
返回:
['Block {\n line 1\n line 2\n line 3\n}\n']
但如果字符串的块部分中有另一个花括号,则表达式将中断,返回空列表:
data ="""
Somewhere over the rainbow
Way up high
Block {
line 1
line 2
{{}
line 3
}
And the dreams that you dreamed of
Once in a lullaby
Block {
line 4
line 5
{{
}
line 6
}
Somewhere over the rainbow
Blue birds fly
And the dreams that you dreamed of
Dreams really do come true ooh oh
"""
如何修改这个regex表达式使其忽略块中的括号,而每个块作为result
列表中的单独实体返回(这样每个块都可以单独访问)?你知道吗
这不管用吗?你知道吗
regex = re.compile("""(Block\ {\n\ [^\}]*\n}\n)""", re.MULTILINE)
在您发布的版本中,每当遇到第二个左大括号时,它就会退出比赛,即使您希望它在第一个右大括号时退出。如果你想要嵌套的大括号,那就另当别论了。你知道吗
相关问题 更多 >
编程相关推荐