Search code examples
regexnotepad++

Regular Expression to find number after word with special characters and subtract constant value


Using notepad++, trying to find number after word with special characters and then subtract constant number from the value for all such occurrence.

Input:

<title>100
<title>99
<title>98
<title>97

Expected output after regex, using find and replace:

<title>78
<title>77
<title>76
<title>75

There is always a difference of 22 between input number and the output.

Tried using below expression, but it only finds all the word with special characters that has < and > before and after.

<(.+?)>

Any suggestions will be helpful.


Solution

  • You can run a python script within the PythonScript plugin.

    If it is not yet installed, follow this guide

    • Create a script (Plugins >> PythonScript >> New Script)
    • Copy this code and save the file (for example substract.py):
    import re
    
    def substract(match):
        val = int(match.group(1)) - 22
        return str(val)
        
    editor.rereplace(r'<title>\K(\d+)', substract)
    
    • Open the file you want to modify
    • Run the script (Plugins >> PythonScript >> Scripts >> substract)
    • Done