regex recursive matching (regex 2015.07.19)

MRAB python at mrabarnett.plus.com
Tue Aug 18 12:36:18 EDT 2015


On 2015-08-18 15:25, Neal Becker wrote:
> Trying regex 2015.07.19
>
> I'd like to match recursive parenthesized expressions, with groups such that
> '(a(b)c)'
>
> would give
> group(0) -> '(a(b)c)'
> group(1) -> '(b)'
>
> but that's not what I get
>
> import regex
>
> #r = r'\((?>[^()]|(?R))*\)'
> r = r'\(([^()]|(?R))*\)'
> #r = r'\((?:[^()]|(?R))*\)'
> m = regex.match (r, '(a(b)c)')
>
>   m.groups()
> Out[28]: ('c',)
>
You can't capture them into different groups in the general case; it
won't create capture groups dynamically.

Capture into 1 group and then use the .captures method:

import regex

r = r'(\([^()]*(?:(?R)[^()]*)*\))'
m = regex.match(r, '(a(b)c)')

print(m.captures(1))




More information about the Python-list mailing list