Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Replace using function

2011-08-21
2013-01-25
  • 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, m.group(1) is the first matching group 
    # (in this case the number), and m.group(0) is always the entire found string
    # (so in this case N[number])
    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)