Replace using function

  • This is just a quick script to demonstrate using a function to calculate the replacement string.  I'm posting it here, just so I can refer to it in the N++ open discussion / help forums when someone asks how to do a replacement that needs computation.

    # Demo to use the results of a function as the replacement text.
    # We'll search for 'N' followed by a number, and return a string with
    # 'D' followed by the number doubled.
    # So, The text "This is N32 which references N15" 
    # Will become  "This is D64 which references D30"
    # The replacement function gets a Regex Match object as a parameter
    # and returns the complete replacement string. 
    # Therefore, in this example, is the first matching group 
    # (in this case the number), and is always the entire found string
    # (so in this case N[number])
    def replace_func(m):
            return 'D' + str(int( * 2)
    editor.pyreplace('N([0-9]+)', replace_func)