This should work for simple cases (no newlines inside single quotes, no single quotes in comments):
#!/usr/bin/perl use warnings; use strict; while (<DATA>) { my $last = (split /'/)[-1]; print $1 if $last =~ /(--.*)/; } __DATA__ select 'text' from foo --This is a comment select '--Not a valid comment' from foo --But this is select q from z -- as is this select '--This is not a valid comment' from foo select '--Not this' + '--either' from foo
Updated.
To handle single quotes in comments, you might need to change the script to the following:
#!/usr/bin/perl use warnings; use strict; while (<DATA>) { my @items = split /'/; until (not @items or $items[0] =~ s/.*?--/--/) { shift @items for 1, 2; # Remove the quoted part, too. } print join "'", @items; } __DATA__ select 'text' from foo --This is a comment select '--Not a valid comment' from foo --But this is select q from z -- as is this select '--This is not a valid comment' from foo select '--Not this' + '--either' from foo select 'qaws' + make from "a" -- comment with 'a' quote select 'a' from 'b' with 'c' -- comment with 'a --' comment
To get the code instead of the comments, just invert the logic:
while (<DATA>) { chomp; my @code; my @items = split /'/; until (not @items or $items[0] =~ s/--.*//) { @items and push @code, shift @items for 1, 2; } print join("'", @code), @items ? (@code ? "'" : q() ) . "$items[0] +" : q(), "\n"; }
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

In reply to Re: Regex: Identifying comments by choroba
in thread Regex: Identifying comments by zuma53

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.