test if an input string starts with a python expression

r0g aioe.org at technicalbloke.com
Mon Dec 7 20:22:23 EST 2009


Torsten Mohr wrote:
> Hi,
> 
> i'd like to test if an input string starts with a python expression
> and also where that expression ends.  An example:
> 
> a_func(3*7, '''abc''') +5 pls some more
> 
> The first part until (inclusive) the 5 should be found as an expression
> and the length of that string should also be detected.
> 
> 
> Background is that i want to embed some python expressions in a text
> and i want to evaluate them later.
> It is possible that the embedded expressions span several lines.
> 
> Alternatively, is it possible to define a start- and an end-marker
> that define the embedded expression and find the expression using
> a regular expression?


That's the easy way and will work for most cases if you use uncommon
delimiters. I tend to use '<<<' and '>>>' for things like this but you
can make them as obscure as you like.



> If the expression contains strings, these strings could contain
> the end-marker which should not be found inside strings.


You could build in escaping but that complicates things quite quickly,
assuming this is for your own private use and you won't be dealing with
huge rafts of data from elsewhere or using this to control radiotherapy
machines etc, that's probably overkill.


The re module should do everything you need and is part of the standard lib.


>>> import re
>>> regex = re.compile(r'<<<(.{1,500}?)>>>', re.DOTALL)
>>> regex.findall("the cat <<<sat>>> on the <<<mat>>>")
['sat', 'mat']

Hope this helps,

Roger.



More information about the Python-list mailing list