在使用正则表达式和双括号时遇到一些麻烦

时间:2016-04-06 05:48:20

标签: python regex nested

我对正则表达式有一些经验,但我无法想出以下内容。如果我有一个字符串:

'[[1,2,3],[3,5,3],[9,8,9]] aoeu [5,6,9] aoeu [[4,5,5]]'

正则表达式模式将单独提取[[1,2,3],[3,5,3],[9,8,9]][[4,5,5]]? (封闭的双括号内的任何组)。显然,'\[\[.*\]\]'太贪婪了......

2 个答案:

答案 0 :(得分:1)

如果输入完全符合您的模式,那么您可以使用它来制作regex non-greedy

p = re.compile(ur'\[\[.*?\]\]')
test_str = u"[[1,2,3],[3,5,3],[9,8,9]] aoeu [5,6,9] aoeu [[4,5,5]]"
print(re.findall(p, test_str))

要处理[[1,2,3],[3,5,3],3][1,2,3,[3,5,3],3]等情况,请使用此正则表达式

(\[[^\[\]]*\[.*?\][^\]\[]*\])

<强> REGEX DEMO

<强> IDEONE DEMO

答案 1 :(得分:1)

如果你能够使用 Matthew Barnett (更好)regex module,你可以想出一些\G魔法:

(?:(?:\[)|(?!\A)\G)[^][]*(\[[^]]+\])

细分并使用Python代码,这将是:

import regex as re

rx = re.compile(r"""
    (?:             # non capturing group
        (?:\[)      # an open bracket
        |           # OR
        (?!\A)\G    # make sure it's not the beginning... 
                    # ...and that it is the start of the last match
    )
    [^][]*          # not a [ or ]
    (\[[^]]+\])     # capture anything between two brackets
    """, re.VERBOSE)

string = '[[1,2,3],[3,5,3],[9,8,9]] aoeu [5,6,9] aoeu [[4,5,5]]'

matches = [match.group(1) for match in rx.finditer(string)]
print matches
# ['[1,2,3]', '[3,5,3]', '[9,8,9]', '[4,5,5]']

另请参阅 demo on regex101.com