Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notepad++ regex replace with captures from the same file

I have a file with the following lines (condensed example, real file is 1.000+ lines):

...
type1.value1=60  <-- replace 60 with 72 from line 5
type1.value2=15  <-- replace 15 with 14 from line 6
type2.value1=50  <-- replace 50 with 72 from line 5
type2.value2=18  <-- replace 18 with 14 from line 6
type3.value1=72  
type3.value2=14
...

I want to replace all values from type(x) with the values from type3. There are many type/value combinations, so i would like to avoid handwork. Also, i have to do this really often.

Is that possible with Notepad++ Regex find/replace?

The matching expression is the following, where the first group should stay the same and the second should be replaced by the result of yet anoter regex.

^type1.([\w]+)=([\S]+)
like image 441
Harper Avatar asked Aug 30 '18 08:08

Harper


1 Answers

Regex:

type(?!3\.)\d+\.value(\d+)=\K\d+(?=[\s\S]*?type3\.value\1=(\d+))

Replace with:

\2

Explanation:

  • type(?!3\.)\d+ Match a type other than 3
  • \.value(\d+)= Match every thing up to = but capture digits
  • \K Forget matches up to now
  • \d+ Match following digits
  • (?= Start of positive lookahead
    • [\s\S]*? Match anything lazily
    • type3\.value\1= Up to the same value of type3
    • (\d+) Then capture its value in CP #2
  • ) End of positive lookahead

Live demo

The point is matching valueX from a type different than 3 then look for the same valueX from type3. If valueX is hypothetical or there isn't anything special to be looked, then there is no pure approach using regex in a find / replace functionality.

like image 117
revo Avatar answered Nov 10 '22 23:11

revo