Introduction
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;
Problem
When a JavaScript file contains regular expressions, say a replace statement on a string:
// Here are some comments
var strText = "fee fi fo fum"; // More
strText = strText.replace (/fee/i, "pee"); // More
alert (strText); /* More */
problems can arise with this parsing mechanism. The problem? Regular expressions with quotes. For example:
// Here are some comments
var strText = "My \"big\" example"; // More
strText = strText.replace (/"/gi, "'"); // 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).
Question
How do we modify this beautiful comment-extracting regex, which generally works on 75%+ of the JavaScript out there, to handle regular expressions such as split(), match(), replace(), search() and test()?
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):
Sample JavaScript File
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);
}