>>> import regex
>>> # The regex behavior version seems to make no difference in this case, so both '(?V0)...' and '(?V1)...' will work.
>>> 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')]
[' ', ' ', ' ', ' ']
>>> s = 'abc and 123 {foo-bar bar baz } bit {yummi tummie} byte.'
>>> inside_braces = re.findall(r'\{.*?\}', s)
>>> spaces_inside_braces = [re.findall(r' +', match) for match in inside_braces]
>>> [match for mlist in spaces_inside_braces for match in mlist] # flatten list
[' ', ' ', ' ', ' ']
如果您可以使用alternate regex module,那么您可以使用单个regex来实现它。不过,它很复杂,不可读。但它能正确处理悬垂的牙套。在
regex
模块支持访问捕获组以前的所有匹配项,这对于以下工作至关重要:简单地说,这个regex查找格式为
'{' blanks? ((nonblanks blanks)* nonblanks blanks?)? '}'
的匹配项,并将所有空白部分分配给名为u
((?P<u>...)
)的同一个捕获组。在它还可以处理包含不匹配的
^{pr2}${
和}
的字符串:在Python 3.5.1 x64、regex 2016.3.2上测试。
A lookahead可以检查前面是否有
}
,中间没有{
。在\s
是空格字符[ \t\r\n\f]
的short。匹配^{如果
(?=[^{]*})
之间有一个}
和任何{a4}之间,则(?=[^{]*})
会向前看。Demo at regex101
r'\{.*?\}'
中的?
来不贪婪地匹配大括号。在{
和{相关问题 更多 >
编程相关推荐