AllanLRH
AllanLRH

Reputation: 1204

Matching the comments of comment out lines

I'd like to match the comments of the comment out lines, when searching in my editor (equivalent of multiline-mode, or so I believe?).

The regex (?<!^)%.+?$ matches the comment of the commented out first line of the following code correctly (Everything after a % is commented out),

 % foo = bar() % First comment

      % baz = qui() % Second commment

but I can't figure out how to also match the second line, assuming it's indented by an unknown number of spaces or tabs.

I tried and failed doing this: ((?<!^)%.+?$|(?<!^\s)%.+?$)

(My previous regex put in a "or-bracket", duplicated and extended to allow for an unknown number of spaces; breaks the regex, as the +and * operators apparently arent allowed in look(ahead|behind)s).

Upvotes: 2

Views: 444

Answers (1)

B8vrede
B8vrede

Reputation: 4532

^\s*%[^%\n]*%(.*?)$ should do the job.

Explanation:

^        # Start of a line
\s*      # 0 or more white spaces
%        # Just a regular % sign
[^%\n]*  # Matches 0 or more times anything that is not a % or a new line (\n)
%        # Just a regular % sign
(.*?)    # Captures everything after the second % (ungreedy)
$        # End of a line (because the previous in ungreedy it will not match items on the new line

This shows look arounds are not always the best approach for certain problems.

I tested it on the following data in Notepad++

% foo = bar() % First comment
% test 
      % baz = qui() % Second commment
someFunction() 

Replacing it with the first captured group results in: (this shows that only the correct parts are captured)

 First comment
% test 
 Second commment
someFunction()

Upvotes: 2

Related Questions