I posted this a bit ago in the regex section, but being unfamiliar with the quoting standards I mangled it a bit. Here it is (hopefully) in readable form.

I am trying to write a regex to remove the comments from lines but I want for people to be able to use the comment character in their input if they comment it ala. perl/c/java backslash metaquoting. I would like a regex to use like s/$regex/$1/ to remove the comments.

As it is I have been using the following (squished a bit to save room):
$m = "\\"; # Meta $c = "\#"; # Comment print "Begin: $_\n"; split /\Q$c\E/; $string = $_ = $_[0]; # Because split puts the first non-blank line +in $_ for($i = 1; $i <= $#_; $i++) { $_ = $_[$i - 1]; (/((^|[^\Q$m\E])((\Q$m\E){2})*$)/) ? (last) : ($string .= "$c" . $_[ +$i]); } print " End: $string\n";
And that has caught every test case I have made up, like:
this is a line with a \# pound # and a comment
this is a \# line with three \#'\#'s # and a comment
this is a line \\\\ with shashes \\\\# and a comment
this is a line \\\\ with shashes \\\# and a pound # and a comment
#this line is only comment
\#this line begins with a pound
\\# This line begins with a slash
\# This line \# \\# has a pound at the beginning
Can anyone come up with a regex to do the same job?

Will

In reply to quoting characters by WHolcomb

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.