how to determine an 'open' string?

holger krekel pyth at devel.trillke.net
Thu May 16 18:21:01 EDT 2002


John La Rooy wrote:
> Oh you changed the return value from 0 to 1 to the left over string ;o)

huh? um, i don't think so. my open_quote returns 
the open *quote* (or '') not the 'left over string'. 

> import re
> 
> def quoteopen(s,quot=re.compile("(?P<quot>\"\"\"|'''|\"|').*?(?P=quot)")):
>     return quot.sub("",s)

> Noone has really discussed why simply counting the quotes is wrong. The
> reason is that while scanning the string from left to right, if you come
> across a quote you have to ignore all the *other* types of quotes until
> you find a matching one. That's what the x!=y in Holger's solution is 
> checking for, and the (?P<quot>...).*?(?P=quot) does in mine.

only the regex is too hungry. it eagerly matches """a"a"" although 
we don't want it to.

> One thing that is missing here is if there is an escaped quote in the string.
> Neither of the regexps here look for them. Holger said he wanted it to work
> like python strings.
> 
> Only Holger knows ;o) Do you need to check for escaped quotes Holger?  

yes and i thought that open_quote does it correctly. not?
the reason i need normal python semantics is that it is
for a 'commandline-completion' module. So it should
e.g. work correctly for the regexes we are talking about :-)

> [me]
> > 
> > def open_quote(text, rex=re.compile('"""|\'\'\'|"|\'')):
> >     """ return the open quote at the end of text.
> >         if all string-quotes are matched, return the
> >         empty string. Based on ideas from Harvey Thomas.
> >     """
> >     rfunc = lambda x,y: x!=y and (x or y) or ''
> >     quotes = rex.findall(text)
> >     return quotes and reduce(rfunc,quotes) or ''

    holger





More information about the Python-list mailing list