我正在尝试使用正则表达式从 javascript 文件中提取函数名称。
2个案例是
案例一:
{ 'test1': function(){},
'test2': function(){}
}
案例 2:
{ test1: function(){}
test2: function(){}
}
两种情况的预期结果:[test1, test2]
现在,当我将此正则表达式与此 javascript 代码一起使用时
contents.match(/(.+)(?=: function\()/g);
我得到的当前结果是
[ '\t\'test1\'',
'\t\'test2\'']
我如何获得预期结果: [test1, test2] ,不包括像\t\' 这样的特殊字符
提前致谢
最佳答案
捕获任何字符串(不是空格,也不是 '
或 "
),当它后面可能跟有 '
或 时"
、任何空格和 : function
let contents = `
{ test1:function(){}
'test2' : function(){}
"tes-t2": function(){}
"teè#//st2" : function(){}
}
`
console.log(contents.match(/([^'"\s]+)(?=['"]?\s*:\s*function\()/g))
关于javascript - 使用单个正则表达式仅提取函数名称(字符串值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383098/