Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何获得箭头函数';谁的身体像一根绳子?_Regex_Reflection_Ecmascript 6_Arrow Functions - Fatal编程技术网

Regex 如何获得箭头函数';谁的身体像一根绳子?

Regex 如何获得箭头函数';谁的身体像一根绳子?,regex,reflection,ecmascript-6,arrow-functions,Regex,Reflection,Ecmascript 6,Arrow Functions,如何将代码作为arrow函数的{}之间的字符串获取 var myFn=(arg1,..,argN)=>{ /** *Want to parse * ONLY which is between { and } * of arrow function */ }; 如果很容易解析简单函数的主体:myFn.toString().match(/function[^{]+\{([\s\s]*)\}

如何将代码作为arrow函数的
{}
之间的字符串获取

var myFn=(arg1,..,argN)=>{
         /**
          *Want to parse
          * ONLY which is between { and }
          * of arrow function 
         */ 

 };
如果很容易解析简单函数的主体
myFn.toString().match(/function[^{]+\{([\s\s]*)\}$/)[1];
就足够了。但是,Arrow函数的定义中不包含
函数
关键字。

这是我的尝试:

函数getArrowFunctionBody(f){
常量matches=f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){([\s\s]*)}?$/);
如果(!匹配){
返回null;
}
const firstPass=匹配[1];
//需要,因为RegExp不处理最后一个“}”。
康斯特第二通行证=
(firstPass.match(/{/g)| |[])。长度===(firstPass.match(/}/g)| |[])。长度-1?
firstPass.slice(0,firstPass.lastIndexOf('}'):
第一关
返回第二通行证;
}
常数K=(x)=>(y)=>x;
常数I=(x)=>(x);
常数V=(x)=>(y)=>(z)=>z(x)(y);
常数f=(a,b)=>{
常数c=a+b;
返回c;
};
const empty=()=>{return undefined;};
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));

log(getArrowFunctionBody(空))我来找一个解决方案,因为我不想写一个,但我没有被公认的答案说服。对于任何对ES6 1-liner感兴趣的人,我编写了这个方法,它可以处理我需要的所有情况——普通函数和箭头函数

const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4');

字符串是独立的,还是更大文本的一部分?为什么要这样做?@FelixKling:For this=>为什么不使用解析器就试图解析JS?How to do parser?适用于所有情况,除非没有像
()=>{/*…*/}
@AbdennourTOUMI这样的参数。我已经更新了答案。