Incognito has asked for the wisdom of the Perl Monks concerning the following question:
This is the code taken from Mastering Regular Expressions book, used to remove all comments from a file (stored in a string).
$data =~ s{ # First, we'll list things we want # to match, but not throw away ( [^"'/]+ # other stuff | # -or- (?:"[^"\\]*(?:\\.[^"\\]*)*" [^"'/]*)+ # double quoted string | # -or- (?:'[^'\\]*(?:\\.[^'\\]*)*' [^"'/]*)+ # single quoted constant ) | # or we'll match a comment. Since it's not in the # $1 parentheses above, the comments will disappear # when we use $1 as the replacement text. / # (all comments start with a slash) (?: \*[^*]*\*+(?:[^/*][^*]*\*+)*/ # traditional C comments | # -or- /[^\n]* # C++ //-style comments ) }{$1}gsx;
When a JavaScript file contains regular expressions, say a replace statement on a string:
problems can arise with this parsing mechanism. The problem? Regular expressions with quotes. For example:// Here are some comments var strText = "fee fi fo fum"; // More strText = strText.replace (/fee/i, "pee"); // More alert (strText); /* More */
If the JavaScript being parsed contained a quote in a regex, then it thinks we have a double quoted or single quoted string, so the comments are left in the file (which is not what we want).// Here are some comments var strText = "My \"big\" example"; // More strText = strText.replace (/"/gi, "'"); // More alert (strText); /* More */
Ultimately the goal would be to parse through this simple JavaScript file containing comments and functions using the regular expressions mentioned above, and leaving it only with pure code (no comments):
function BadQuoteTest (strInput) { strInput = strInput.replace(/"/gi, "'"); // aka aaa; /* This stuff is commented out so should be parsed out strInput = strInput.replace(/x/gi, "y"); // aka bbb; */ return (strInput); } function splitTest (strInput) { var pattern = /\s*;\s*/gi; return (strInput.split (pattern)); // Test } function splitTestWithLimit (strInput) { return (strInput.split (/\"/gi, 3)); // Test } function matchTest () { var strText = 'Cool text'; strText = strText.match (/oo/gi); // Test alert (strText); } function searchTest () { var strText = "Search text"; // Test strText = strText.search (/x/gi); // Test alert (strText); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: Extracting C Style Comments Revised (JavaScript)
by tye (Sage) on Oct 23, 2001 at 23:05 UTC | |
|
Re: Extracting C Style Comments Revised (JavaScript)
by Fletch (Bishop) on Oct 23, 2001 at 22:34 UTC | |
|
Re: Extracting C Style Comments Revised (JavaScript)
by Tetramin (Sexton) on Oct 24, 2001 at 00:08 UTC | |
by Incognito (Pilgrim) on Oct 24, 2001 at 00:36 UTC | |
by Tetramin (Sexton) on Oct 24, 2001 at 01:32 UTC | |
by Incognito (Pilgrim) on Oct 24, 2001 at 03:35 UTC |