notepad++

Modify indexes in python script using notepad++


I have a Python script which reads data from a database into a list and fills a template. The database structure changed so now I have to add 2 to all indexes. Is there a way to do such thing using notepad++?

What I have is something like:

cursor.execute("SELECT * FROM mytable WHERE id = %s",id)
row = cursor.fetchone()
nameSpace = {'valone':str(row[1]),'valtwo':str(row[2]),'valthree':str(row[3]),} #and so on

And I need it to be:

cursor.execute("SELECT * FROM mytable WHERE id = %s",id)
row = cursor.fetchone()
nameSpace = {'valone':str(row[3]),'valtwo':str(row[4]),'valthree':str(row[5]),} #and so on

There's over a hundred variables, so I don't want to do it manually.

Thanks in advance ;)


Solution

  • You may use a simple regex like \w+\[([0-9]+)] and use a PythonScript to process these matches, incrementing the number inside Group 1.


    def increment_2_up(match):
        return '%s%s]'%(match.group(1), str(int(match.group(2))+2))
        
    editor.rereplace(r'(\w+\[)([0-9]+)]', increment_2_up)
    

    Now, run the script from *Plugins* -> *Python Script* -> *Scripts* -> *increment_numbers_2up*

    I got this result: nameSpace = {'valone':str(row[3]),'valtwo':str(row[4]),'valthree':str(row[5]),} #and so on

    Pattern details:

    The Python code here - str(int(match.group(2))+2) - parses the digits captured into Group 2 with int(match.group(2), then adds 2, and casts the value to a string with str().