Charles
Charles

Reputation: 1229

Regexp puzzle : encapsulated structures

So here I am trying to do something all programmers probably had to done as well one day.

I have all those nested macros in my code and I want to comment next to each #endif which #if it closes - if there is no comment yet. Can a regexp do that for me ? Until now * and + have been too greedy in Notepad++, even if I used the theoretically lazy version *? and +? ...

For example this

#if A

Code

#if B

Code

#if C

Code

#endif

Code

#endif /* B */

Code

#endif

Into this

#if A

Code

#if B

Code

#if C

Code

#endif /* C */

Code

#endif /* B */

Code

#endif /* A */

Upvotes: 0

Views: 70

Answers (1)

Leo Aso
Leo Aso

Reputation: 12463

Can this be done with a single regular expression? Hell no!

Can this be done in Notepad++ using only regular expressions? HELL YEAH!!!

  1. Turn OFF . matches newline.
  2. Replace all \r\n with \n. This makes the regular expressions much simpler on Windows. You can change them back later if you want.

  3. Clear all existing #endif markings by replacing ^#endif.* with #endif.

  4. We need to focus on only #if... and #endif lines, so we ignore all the others by replacing ^(?!#(if|endif)).* with ;$0. So ; is our 'ignore' marker.

  5. Next, we repeatedly alter #if - #endif pairs that only have ignored lines between them.
    So, repeatedly 'Replace All'
    ^#if(.+)\n((;.*\n)*)#endif
    with
    ;#if$1\n$2;#endif /* $1 */.

    This applies the comment to all #if - #endifs at the lowest nesting level, and then marks them with ;, so the next time you click 'Replace All', they are ignored.
  6. When you are done, remove the ignore markers by replacing ^;(.+?\n) with $1.

VOILA!

Upvotes: 1

Related Questions