Jack
Jack

Reputation: 11

Perl Regex remove c comments with specific keywords

I have text like so:

  1. /* blah blah blah blah */
  2. /* blah blah blah jjj blah blah*/
  3. /* blah blah*/
  4. /* blah jjj
  5. blah blah */
  6. /* blah blah*/

I'd like to use perl regex to remove sections that start with /* ,contain jjj and end with */ (remove c comments that contain specific keywords...) in the above example, I would want only lines 2, 4 and 5 to be removed

Your help is most appreciated,

Jack

Upvotes: 1

Views: 575

Answers (1)

Seth Robertson
Seth Robertson

Reputation: 31461

In general this is not very possible. The C parse is very complicated with special handling due to comments, continuation lines, etc.

However, if you have a simple enough case, you might be able to do it. I leave "// blah jjj" comment processing for you since you didn't mention it.

while ($ccode =~ s/(.*?)(\/\*.*?\*\/)//s)
{
   $out .= $1;
   my $comment = $2;
   $out .= $comment unless ($comment =~ /\bjjj\b/);
}
$out .= $ccode;

Upvotes: 4

Related Questions