Javascript 从函数定义中获取参数列表的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13952870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular Expression to get parameter list from function definition
提问by Jason L.
Possible Duplicate:
How to get function parameter names/values dynamically from javascript
I'm currently working on a project in javascript (node.js) that has me trying to get an array of parameter names(NOT values, I do not need arguments) from a function. I'm currently using Function.toString() to get the function string and then running a regex against that to get my parameter list.
我目前正在 javascript (node.js) 中处理一个项目,该项目让我尝试从函数中获取参数名称数组(不是值,我不需要参数)。我目前正在使用 Function.toString() 来获取函数字符串,然后针对它运行正则表达式来获取我的参数列表。
Let's take the following SIMPLE example:
让我们以下面的简单示例为例:
var myFunction = function (paramOne, paramTwo) { ... }
Running my regex against this, and then doing some string magic (split, etc) I would expect an array back like this:
针对此运行我的正则表达式,然后执行一些字符串魔术(拆分等),我希望数组返回如下所示:
paramList = ['paramOne', 'paramTwo']
I have something that works but I'm feeling like it's probably not the best solution given some of the funky characters javascript lets you use for variable names and that javascript will let you define functions on multiple lines.
我有一些有用的东西,但我觉得它可能不是最好的解决方案,因为 javascript 允许您将一些时髦的字符用于变量名,并且 javascript 可以让您在多行上定义函数。
Here is what I currently have:
这是我目前拥有的:
function.*[\w\s$]*(\((.*[\w\s,$]*)\))
This gives me my "match" in group 1 and then my param list without parens in group 2, which is cool. Is this really the best way to do what I want? Is there a better regular expression I could use for this? I'm not really looking for something "simpler" but really just something that could catch all possible situations.
这给了我第 1 组中的“匹配”,然后是第 2 组中没有括号的参数列表,这很酷。这真的是做我想做的最好的方法吗?有没有更好的正则表达式可以用于此目的?我并不是真的在寻找“更简单”的东西,而只是寻找可以捕捉所有可能情况的东西。
Any help would be appreciated, and many thanks in advance!
任何帮助将不胜感激,并在此先感谢!
回答by T.J. Crowder
The easiest thing would be to capture everything in the first set of parens, and then use split(/\s*,\s*/)to get the array.
最简单的方法是捕获第一组括号中的所有内容,然后用于split(/\s*,\s*/)获取数组。
E.g.:
例如:
var str = "function( one ,\ntwo,three , four ) { laksjdfl akjsdflkasjdfl }";
var args = /\(\s*([^)]+?)\s*\)/.exec(str);
if (args[1]) {
args = args[1].split(/\s*,\s*/);
}
snippet.log("args: " + JSON.stringify(args));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
How the above works:
上面的工作原理:
We use
/\( *([^)]+?) *\)/to match the first opening parenthesis (\(since(is special in regexes), followed by any amount of optional whitespace, followed by a capture group capturing everything but a closing parenthesis (but non-greedy), followed by any amount of optional whitespace, followed by the closing).If we succeed, we split using
/\s*,\s*/, which means we split on sequences which are zero or more whitespace characters (\s*) followed by a comma followed by zero or more whitespace characters (this whitespace thing is why the args in my example function are so weird).
我们
/\( *([^)]+?) *\)/用来匹配第一个左括号(\(因为(在正则表达式中是特殊的),然后是任意数量的可选空格,然后是捕获组,捕获除右括号之外的所有内容(但非贪婪),然后是任意数量的可选空格,其次是闭幕)。如果我们成功了,我们使用 拆分
/\s*,\s*/,这意味着我们拆分零个或多个空白字符 (\s*) 后跟逗号后跟零个或多个空白字符的序列(这个空格就是为什么我的示例函数中的 args 如此奇怪) .
As you can see from the example, this handles leading whitespace (after the (and before the first argument), whitespace around the commas, and trailing whitespace — including line breaks. It does nottry to handle comments within the argument list, which would markedly complicate things.
从示例中可以看出,这会处理前导空格(在(第一个参数之后和之前)、逗号周围的空格和尾随空格 - 包括换行符。它并没有试图处理参数列表中的注释,这将显着复杂的事情。
Side note: Be sure to test on your target browsers, Function#toStringreturning some form of the source code is a non-standard feature. It's broadly supported (in desktop browsers), but not standard. Note that some browsers will include comments, others will not; if someone includes comments in the function arguments, it could well mess up your parsing of them. You might kick around the Prototype source code for its Function#argumentNamesextension, as they've already been down this road...
旁注:请务必在您的目标浏览器上进行测试,Function#toString返回某种形式的源代码是一项非标准功能。它被广泛支持(在桌面浏览器中),但不是标准的。请注意,有些浏览器会包含注释,有些则不会;如果有人在函数参数中包含注释,则很可能会破坏您对它们的解析。您可能会为它的Function#argumentNames扩展程序打开Prototype 源代码,因为它们已经沿着这条路走下去了……
回答by closure
Do as following:
执行以下操作:
var ar = str.match(/\((.*?)\)/);
if (ar) {
var result = ar[0].split(",");
}
Remember ? after * does a non greedy find
记住 ?在 * 之后进行非贪婪查找
回答by shybovycha
Let me suggest you using regular expressions:
让我建议您使用正则表达式:
- [match]
/function[^(]*\(([^)]*)\)/will match the argument list - [split]
/\W+/(against the results of the first match data) will split the match into params list
- [match]
/function[^(]*\(([^)]*)\)/将匹配参数列表 - [split]
/\W+/(针对第一个匹配数据的结果)将匹配拆分为 params 列表
So, the code should look like this:
所以,代码应该是这样的:
var s = "function moo (paramOne, paramTwo) { alert('hello'); }";
var s2 = s.match(/function[^(]*\(([^)]*)\)/)[1];
var paramList = s2.split(/\W+/);

