Regexp to check if a string is a javascript function?
I want to check if a string is a valid javascript function call.
Could someone help me to write a regex that match to all these:
hello("hello", "world")
greet(1, "mr", "peterson开发者_开发问答");
run()
But not these:
walk()); // invalid syntax
greet(1?23\) // invalid js characters
say("hi" -) // invalid js characters
Thanks!
Answering the implied question from your comment:
I want to use eval() on it. But I want to check its valid js function first because I dont want to run variables or invalid strings.
If this is one of the, oh, three (or fewer) valid places where using eval
isn't a bad idea, probably better to go ahead and eval
it and handle the resulting Error
via a try/catch
block — EvalError
, SyntaxError
, etc. See the spec for details of the various errors — if you care what the error is; mostly I'd think you just want to know whether there was a problem or not, e.g.:
try {
eval(theString);
}
catch (e) {
// Something went wrong, report it
}
But: You can (and should) almost always avoid using eval
. For instance, if you want to allow someone to give you something to call that may require arguments (your hello("hello", "world")
), just have them give you a function you call without arguments, and they would give you a wrapper e.g.:
callTheFunction(function() {
hello("hello", "world");
});
You can define the folloding regexp for a parameter, meaning string or integer or float or variable
string literal : "[^"]"
int : -?\d+
float : -?\d*\.\d+
variable / function name : [\w\d_]+
parameter : ("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)
Then your function is the same as a variable, followed by parenthesis a few parmeters, then closing parenthesis.
rough : function \( (|parameter(,parameter)*\)
adding potential spaces : function\s*\(\s*(|parameter\s$(,\s*parameter\s*)*\)
replacing blocks : [\w\d_]+\s*\(\s*(|("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)\s$(,\s*("[^"]"|-?\d+|-?\d*\.\d+|[\w\d_]+)\s*)*\)
Note that you will want to match multiline and case insensitive. I don't ensure it's error-proof, but at least you can follow the kind of thinking you have to deal with to fine tune it.
EDIT : I thought it was fairly complex (I probably issed some cases), but after your comment, if it's just to run eval, it's pointless... note that my checks only assume that you use plain variables, no objects (otherwise, deal with the dot which can't be in first position)
精彩评论