Thanks for your help first!
I have some jscripts like:
var id="001";
var name="Jerry";
...
function f1() {
...
var qid="q1";
...
}
...
var qid="aaabbb";
...
function f2(){
...
var myid="q1";
...
}
...
I want to use regular expression to get the names of function that contains key word "q1". Is there a simple way to do so?
Functions can be defined within other functions in JavaScript, so using regular expressions to try to solve this problem is impossible. Sorry :-(
Also, the problem is underspecified. What function name do you want in a case like this?
function outerFunction(x, y) {
var innerFunction = function(z) {
return {
firstProperty: function() {
return "q1";
}
};
};
}
See? Three different ways to declare a function. How would you create a solution general enough to know the "correct" (most relevant) function name for cases like this?
Here's the regex that seems to work for me:
(function(.*)\(.*|
*"q1")
and here's how I tested it:
Try the following:
/^function ([^(]*?)\((?=(?:[^
]|
[^}])*("q1")).*?^}/ms
Note that this does not match "q1" when it is outside of a function, or function names that don't have "q1" inside. For each match the first group will be the function name and the second group will be "q1".
See it in action: http://rubular.com/r/xQwro38DUO
Here is an explanation:
$regex = <<<END
/
^function[ ] # start looking when a line starts with function
([^(]*?)\( # capture the function name into group 1
(?= # start a lookahead
(?:[^
]|
[^}])* # consume characters until a line starts with '}'
("q1") # or until we find "q1" (and place it in group 2)
) # end lookahead
.*?^} # consume until end of function (optional)
/msx # m and s flags for consuming multiple line handling
END;