On Dec 8, 1:22 am, r0g aioe@technicalbloke.com wrote:
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.
Use the parser module.
parser.expr('func(a+1)')
parser.st object at ...
parser.expr('print a')
...
SyntaxError: invalid syntax
Quite intensive as you have to compile every initial substring to find
the longest one but at least you use Python's own definition of an
expression.
Chard.
--
http://mail.python.org/mailman/listinfo/python-list