how to determine an 'open' string?

John La Rooy larooy at xtar.co.nz
Thu May 16 18:03:57 EDT 2002


Oh you changed the return value from 0 to 1 to the left over string ;o)
in that case...

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.

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?  


On Thu, 16 May 2002 22:31:29 +0200
holger krekel <pyth at devel.trillke.net> wrote:
> 
> 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 ''
> 
> regards and thanks for all suggestions,
> 
>     holger
> 
> 



More information about the Python-list mailing list