Don't use a single regex. Have a regex for each type of item and parse them out as you go (stealing from myself):

while( $code !~ m#\G$#gc ) { if( $code =~ m#\G//(.*)\n#gc ) { # $1 is end-of-line comment } elsif( $code =~ m#\G"((?:[^"\\]|\\.)*)"#gc ) { # $1 is the inside double quotes } elsif( $code =~ m#\G'((?:[^'\\]|\\.)*)'#gc ) { # $1 is the inside single quotes } elsif( $code =~ m#\G/*(.?)*/#gmc ) { # $1 is a comment } elsif( $code =~ m#\G/((?:[^/\\]|\\.)*)/#gc ) { # $1 is a regex } elsif( $code =~ m#\G([^/'"]+)#gc ) { # $1 is "other code" } elsif( $code =~ m#\G/#gc ) { # division, we hope. } else { # We have hit invalid code? } }
But this can still be fooled, though it is much harder. (:

Update: The only real problem (based on some guesses since I don't know JavaScript syntax) is determining whether a / is starting a regex or is denoting division (I'm assuming that "//" isn't a valid regex and is always an end-of-line comment). This is similar to the problem with parsing Perl, knowing whether the next thing is supposed to be a term or an operator. Perl makes this extra hard because function prototypes can change whether the parser expects a term or operator to follow that function invocation. I doubt JavaScript makes things that hard so someone who understands the syntax could probably fix up my code to work 100% of the time.

To go beyond this, I'd probably start looking into Parse::RecDescent.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Extracting C Style Comments Revised (JavaScript) by tye
in thread Extracting C Style Comments Revised (JavaScript) by Incognito

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.