Dion - 2011-12-10

Hi,
Does anyone know of a way to use a replace function to find a regex and replace with a series of sequential numbers?

I am looking to find a tag in some html text and replace it with a "1", then find the next and replace with a "2", etc.

I saw davegb's example of using a function (https://sourceforge.net/projects/npppythonscript/forums/forum/1199074/topic/4667045)

def replace_func(m)
       try: 
              return 'D' + str(int(m.group(1)) * 2)
       except:
              return m.group(0)
editor.pyreplace('N([0-9]+)', replace_func)

But I can't seem to get a counter to pass into the function, or use some kind of global counter within the function.

def replace_func(m):
                x = 1
        try:
                return "<h3>" + str(x) + "</h3>"
                                x = x + 1
        except:
                return m.group(0)
editor.pyreplace(r"\<h3\>([0-9]+)\.jpg\<\/h3\>", replace_func)

That just replaces everything with "1" because it keeps initializing x=1 each time. Without the X = 1 it doesn't do anything.

To expand upon this, I would also like to have the replacement text referenced  from an array using the counter as the index.

e.g.

1, "I"
2, "II"
3, "III"
4, "IV"
5, "V"
etc.

would result in:

<h3>I</h3>
<h3>II</h3>
<h3>III</h3>
<h3>IV</h3>
<h3>V</h3>

Thanks!