Brackets in brackets, braces in braces

Bengt Richter bokr at oz.net
Tue Apr 16 19:04:48 EDT 2002


On 16 Apr 2002 08:30:05 -0700, ahorvath at szgti.bmf.hu (Horvath, Arpad) wrote:

>How can I find strings like this with regular expressions:\something
>[something1] {something2} {something3}Where in the braces can be also
>another braces. For example:\frac{1\times10^{-16}}{4}   can be at the
>place, where something2 is.(braces in pairs)\interval [J]
>{\frac{1\times10^{-16}}{4}} {1..5}My half solution is at
>www.szgti.bmf.hu/~ahorvath/regexp.txt.

Depending on what your real goal is, you might want to play with
using split and making an actual nested list structure.
E.g., I posted this for a similar question in the past (it just does one
kind of brackets, i.e, braces):

> >>> s = "A line of text with {multiple and {nested} braces} to {confuse} re!"
> >>> sl = eval('["'+'"], "'.join('", ["'.join(s.split('{')).split('}'))+'"]')
> >>> sl
> ['A line of text with ', ['multiple and ', ['nested'], ' braces'], ' to ', ['confuse'], ' re!']

>then walk the tree as desired.

The above uses eval to do the nest counting. You'd have to split on '[' and ']' first, and then
walk the tree and do '{' and '}' processing similarly to expand the first tree's elements, if
you had both kinds of bracketing. Plus you'd want to preserve some kind of indication of what
kind of bracket your final nested lists represented.

Or you could write a recursive parser. Might be fun ;-)
Or you could use a Python flex workalike to do it, I suppose. I haven't tried one yet.

Regards,
Bengt Richter



More information about the Python-list mailing list