Backreferences in python ?

Sion Arrowsmith siona at chiark.greenend.org.uk
Tue Jan 24 04:15:34 EST 2006


Pankaj <pankajgode at gmail.com> wrote:
>search for :    for ( i = 0; i < 10; i++)
>Replace with:  for( printf( "10" ), i =0; i < 10; i++)
>Where 10 is the line no.

>f = open( "./1.c", "r")
>fNew = open( "./1_new.c", "w")
>for l in f:
>        print l
>        lineno = lineno + 1
>        strToFind = "for\((.*)\;(.*)"
[etc.]
>search for :    for ( i = 0; i < 10; i++)
>Replace with:  for( printf( "10" ), i =0; i < 10; i++)

Ah, the dangers of thinking of all string manipulation as requiring
regexps, thanks to their ubiquity in Perl. Observe:
>search for :                  for ( i = 0; i < 10; i++)
>Replace with:  for( printf( "10" ), i = 0; i < 10; i++)

All you need is:
    strToFind = "for ("
    strToReplace = 'for (printf( "+str(lineno)+'" ),'
    # Note the use of '' to avoid the need to escape the "s
    fNew.write(l.replace(strToFind, strToReplace)

(OK, maybe you do need the regexp if you've got any "for (;" loops,
or inconsitencies as to whether it's "for(" or "for (". But if a
simple string replace will do the job, use it.)

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list