0

I found many references on replacing with regex but I could not find a way to do what exactly I need.

For example I have txt with about 15k bits of code i need to change all need -1 their current value.

is_magic = 0 mp_consume2 = 9

In this case 9 would need to be changed to 8. There are thousands of these ranging in value from 6 up to 250. is_magic defines its type and needs to be included or the changes would be applied to other groups where the change is not needed.

I tried various regex and wildcard examples but always it in some way, shape or form broke the file, and starting to lose hair. Maybe this just cannot be done with Notepad++ ?

Dehay
  • 11
  • 4
  • Regexp might not be sufficient here, since it is not capable of math. You can parse the file by `perl`, extract the numbers with `regex` and perform the calculations outside the `regex`. – Nemesis Nov 14 '14 at 16:29

2 Answers2

0

Regex doesn't do math. However, some brute force methods, and language specific methods, produce results.

Math operations in regex

Community
  • 1
  • 1
Kennah
  • 487
  • 1
  • 5
  • 16
0

This can be done in Perl with a regular expression in a substitution.

The question is not clear whether there is only one number per line to be decremented nor whether it is the last part of the line. So below are two ways of doing the decrement in Perl.

The first way handles several numbers on one line. The second way only operates on lines starting "is_magic = 0 mp_consume2 = " and where the number is he last part of the line.

use strict;
use warnings;

my $s = "is_magic = 0 mp_consume2 = 9 abc = 5 def = 6 ghi = 125 jkl = 250 zz\n";
print $s;
$s =~ s/ = (\d+)\b/" = " . ( $1 >= 6 && $1 <= 250 ? $1-1 : $1)/eg;
print $s;

my @t = ( "is_magic = 0 mp_consume2 = 9\n",
          "is_not_magic = 0 mp_consume2 = 9\n" );

foreach my $u ( @t )
{
    print "\n";
    print $u;
    $u =~ s/^(is_magic = 0 mp_consume2 = )(\d+)$/$1 . ( $2 >= 6 && $2 <= 250 ? $2-1 : $2)/e;
    print $u;
}

The interesting part is e within the s/.../.../e. That means the replacement is an expression. The expression is the concatenation (using .) of two strings. The right hand string is made by range checking the matched number and decrementing it when in range, otherwise leaving it unchanged.

AdrianHHH
  • 13,492
  • 16
  • 50
  • 87