Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notepad++ Regular Expression add up numbers

How do I sum or add a certain value to all those numbers? For example my goal is to increase all those numbers inside the "" with 100 but achieving that has been problematic. Basically just somehow sum the current number with +100.

I have the following lines

<devio1="875" devio2="7779" devio3="5635" devio4="154"/>
<devio1="765" devio2="74779" devio3="31535" devio4="544"/>
<devio1="4335" devio2="13" devio3="55635" devio4="1565"/>

By using this regular expression with Notepad++

<devio1="([0-9]+)" devio2="([0-9]+)" devio3="([0-9]+)" devio4="([0-9]+)"/>

I can find all the numbers inside the "" but I cannot find a way to add +100 to all of them. Can this task be achieved with Notepad++ using Regular Expressions?

like image 772
user3088879 Avatar asked Dec 10 '13 22:12

user3088879


2 Answers

That's not possible with the sole use of regular expressions in Notepad++. Unfortunately there's no way to perform calculations in the replacement pattern.

So the only way of accomplishing your task in Notepad++ is with the use of the Python Script plugin.

  1. Install Python Script plugin from the Plugin Manager or from the official website.
  2. Then go to Plugins > Python Script > New Script. Choose a filename for your new file (eg add_numbers.py) and copy the code that follows:

    def calculate(match):
        return 'devio%s="%s"' % (match.group(1), str(int(match.group(2))+100))
    
    editor.rereplace('devio([0-9])="([0-9]+)"', calculate)
    
  3. Run Plugins > Python Script > Scripts > add_numbers.py and your text will be transformed to:

    <devio1="975" devio2="7879" devio3="5735" devio4="254"/>
    <devio1="865" devio2="74879" devio3="31635" devio4="644"/>
    <devio1="4435" devio2="113" devio3="55735" devio4="1665"/>
    
like image 68
psxls Avatar answered Sep 25 '22 06:09

psxls


I'm not really familiar with notepad++ but for an algorithm, supposing you have a number abcd = a*1000 +b*100 + c*10 + d, then so long as b is in [0,8] you can just replace b by b+1. As for when b = 9 then you need to replace b with 0 and replace a with a+1 (and if a = 9 then you'd replace a by 10).

Noting this, you could then, for three and four digit numbers, say, apply the following regexes:

\([1-9]+\)0\([0-9]{2}\) -> \1 1\2, 
\([1-9]+\)1\([0,9]{2}\) -> \1 2\2, 
... -> , 
\([1-9]+\)8\([0-9]{2}\) -> \1 9\2, 

and so on ... Noting that you also have to consider any a=9, b=9 integers, and larger integers; this suggests some sort of iteration with if statements covering the cases where the coefficients of 10^x (x>=2) are equal to 9. When you start actually coding this (or doing it by hand) you will begin to realize that doing this with a pure regex approach is going to be painful.

like image 41
HexedAgain Avatar answered Sep 24 '22 06:09

HexedAgain