如果您可以使用替代正则表达式模块,那么您可以使用单个正则表达式完成它。但是,这很复杂且难以阅读。但它可以正确处理悬挂的大括号。
regex
模块支持访问捕获组的所有先前匹配项,这对于以下内容至关重要:
>>> import regex
>>>
>>> pattern = r'(?V0)[{] (?P<u>\s+)? (?: (?: [^\s}]+ (?P<u>\s+) )* [^\s}]+ (?P<u>\s+)? )? [}]'
>>> string = 'abc and 123 {foo-bar bar baz } bit {yummi tummie} byte.'
>>> [s for m in regex.finditer(pattern, string, regex.VERBOSE) for s in m.captures('u')]
[' ', ' ', ' ', ' ']
简单来说,这个正则表达式可以匹配形式为'{' blanks? ((nonblanks blanks)* nonblanks blanks?)? '}'
的内容,并将所有空格部分分配到同一个名为u
((?P<u>...)
)的捕获组中。
它还可以处理包含未匹配的{
和}
字符的字符串:
>>> # Even works with dangling braces:
>>> badstring = '}oo} { ab a b}} xy {xy x y}cd {{ cd } e{e }f{ f} { }{} }{'
>>> # Fully flattened result:
>>> [s for m in regex.finditer(pattern, badstring, regex.VERBOSE) for s in m.captures('u')]
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
>>> # Less flattened (e.g. for verification):
>>> [v for m in regex.finditer(pattern, badstring, regex.VERBOSE) for v in m.capturesdict().values()]
[[' ', ' ', ' '], [' ', ' '], [' ', ' '], [' '], [' '], [' '], []]
已在 Python 3.5.1 x64 和 regex 2016.3.2 上进行测试。
abc { abc } a { a }
或abc { a { b } }
吗? - Norman