简体   繁体   中英

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, eg:

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 eg:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM