Home > Enterprise >  Regex - Would Like to Match Patterns Across Multiple Lines and Consolidate the Lines
Regex - Would Like to Match Patterns Across Multiple Lines and Consolidate the Lines

Time:07-12

I have a file of program code and would like to use Regex to combine multiple lines. A typical series of lines might look this:

   rp = 10;
   cp = 15;
   wd = 2;
   ht = 1;
   dr = 3;
   ds = 10   5 * x;
   sp = 50;
   er = 1;
   Anim(rp, cp, wd, ht, dr, ds, sp, er);

All the lines except the last assign values to parameters. The last line is a call to function Anim() using the parameters. The file of program code will have multiple instances of blocks of code in this format.

I would like to perform an edit that rewrites the lines that assign values as one line:

   rp = 10; cp = 15; wd = 2; ht = 1; dr = 3; ds = 10   5 * x; sp = 50; er = 1;
   Anim(rp, cp, wd, ht, dr, ds, sp, er);

What makes this challenging is that sometimes the parameters are assigned in a different order. Also, not all the parameters are assigned because they may already have the correct values. So sometimes the program code might look like this:

   cp = 15;
   rp = 10;
   dr = 3;
   sp = 50;
   er = 1;
   Anim(rp, cp, wd, ht, dr, ds, sp, er);

What I can say for sure is that the variables being assigned always have two letters. And the block of lines to be rewritten always has this pattern:

one or more of these:   ^\s*[a-z][a-z]\s*=\s*.*;\r\n   (Note - call this line1 or line2 or ...)

         followed by:   ^\s*Anim(rp, cp, wd, ht, dr, ds, sp, er);\r\n   

and I want to rewrite as:  line; line2; line3;  etc. \r\n     
                           Anim(rp, cp, wd, ht, dr, ds, sp, er);\r\n  

I would be very grateful for any suggestions on how I can use Regex to perform these edits, if possible.

I use Notepad .

Thank you.

CodePudding user response:

  • Ctrl H
  • Find what: (?<!\);)\R(?!\w \()
  • Replace with: A SPACE
  • CHECK Wrap around
  • CHECK Regular expression
  • Replace all

Explanation:

(?<!\);)        # negative lookbehind, make sure we haven't ");" before
\R              # any kind of linebreak (i.e. \r, \n, \r\n)
(?!\w \()       # negative lookahead make sure we haven't a word and a prenthesis after

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

  • Related