使用正则表达式解析function字符串

正则表达式:

/\s*(?:(async)\s+)?function\s+(?:([_$a-zA-Z][_$a-zA-Z0-9]*)\s*?)?\(((?:\s*(?:[_$a-zA-Z][_$a-zA-Z0-9]*)\s*)(?:,\s*(?:[_$a-zA-Z][_$a-zA-Z0-9]*)\s*)*?)\)\s*?\{\s*([\s\S]*)\s*\}\s*/

在线调试:点这里

1、正则表达式

var regexp = /\s*(?:(async)\s+)?function\s+(?:([_$a-zA-Z][_$a-zA-Z0-9]*)\s*?)?\(((?:\s*(?:[_$a-zA-Z][_$a-zA-Z0-9]*)\s*)(?:,\s*(?:[_$a-zA-Z][_$a-zA-Z0-9]*)\s*)*?)\)\s*?\{\s*([\s\S]*?)\s*\}\s*/;

2、测试 String

var functionString = `async function name (param1, param2) {
  console.log(param1, param2);
}`;
// => "async function name (param1, param2) {\n  console.log(param1, param2);\n}"

3、验证

var result = regexp.test(functionString);

4、匹配信息

var result = refunctionString.match(gexp);
/**
 * => [
 *    "async function name (param1, param2) {\n  console.log(param1, param2);\n}",
 *    "async",
 *    "name",
 *    "param1, param2",
 *    "console.log(param1, param2);"
 *  ]
 */

groupNum

isParticipating

content

0

true

"async function name (param1, param2) {\n\tconsole.log(param1, param2);\n}"

1

true

"async"

2

true

"name"

3

true

"param1, param2"

4

true

"console.log(param1, param2);"