in reply to Extracting C Style Comments Revised (JavaScript)
Don't use a single regex. Have a regex for each type of item and parse them out as you go (stealing from myself):
But this can still be fooled, though it is much harder. (: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? } }
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")
|
|---|