is there a simple way to abuse parser for this?

  • Thread starter Alexander Schmolck
  • Start date
A

Alexander Schmolck

I sometimes find myself in the situation that I want to perform some simple
source code changes, queries etc. in the code regions of a python file (i.e.
outside comments and strings).

I thought a reasonable way to achieve this might be to have some simple minded
regexp that does the job but doesn't pay attention to strings (or comments,
but those would usually be relatively easy to handle) and then only check
*after* a match was found whether this match occured in a valid region (since
false positives should be rare).

i.e.:

def replaceStuff(match):
if validRegion(match.start, match.end):
...
else:
return match.group(0)
...
re.sub(regexp, replaceStuff, pythonFile)


I was wondering whether python's parsing services (which I haven't used so
far) could be easily coopted for the ``validRegion`` detection (one could of
course use a regexp to find string and comment boundaries but that has the
disadvantage that it's lest robust, e.g. it might break if new syntax is
introduced).


'as
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top