【问题标题】:Regular expression to find all methods in a piece of code正则表达式查找一段代码中的所有方法
【发布时间】:2009-03-19 07:43:43
【问题描述】:

我正在尝试编写一个正则表达式来匹配构造函数字符串中的所有 JavaScript 方法定义。

//These two should match
this.myMethod_1 = function(test){ return "foo" }; //Standard
this.myMethod_2 = function(test, test2){ return "foo" }; //Spaces before

//All of these should not
//this.myMethod_3 = function(test){ return "foo" }; //Comment shouldn't match
/**
 *this.myMethod_4 = function(test){ return "foo" }; //Block comment shouldn't match
 */

//       this.myMethod_5 = function(test){ return "foo" }; //Comment them spaces shouldn't match

/*
 *        this.myMethod_6 = function(test){ return "foo" }; //Block comment + spaces shouldn't match
 */

this.closure = (function(){ alert("test") })(); //closures shouldn't match

正则表达式应匹配 ['myMethod_1', 'myMethod_2']。正则表达式不应匹配 ['myMethod_3', 'myMethod_5', 'myMethod_6', 'closure']。

这是我目前所拥有的,但我遇到了出现在 cmets 中的问题:

/(?<=this\.)\w*(?=\s*=\s*function\()/g

我一直在用这个很酷的site 来测试它。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript regex parsing


    【解决方案1】:

    正确执行这听起来很复杂。您需要为此创建一个解析器,一个简单的正则表达式很可能无法实现。

    A very good starting point is Narcissus,这是一个用 ... JavaScript 编写的 JavaScript 解析器。

    只有 1000 行代码。应该可以只提取其中与方法匹配的部分。

    【讨论】:

      【解决方案2】:

      在开头添加^\s* 可能会有所帮助。它并不完美,但它适用于您的测试用例。

      【讨论】:

        【解决方案3】:

        一个正则表达式可能难以编写和调试。考虑编写几个正则表达式,每行一个正则表达式应该匹配以确认或拒绝一段代码。

        例如,

        /(?<=this.)\w*(?=\s*=\s*function()/g  // Matches a simple constructor.
        /^\/\// // If it matches then this line starts with a comment.
        

        等等。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-13
          • 1970-01-01
          • 2014-09-17
          • 1970-01-01
          • 2019-01-17
          • 2013-10-27
          • 1970-01-01
          相关资源
          最近更新 更多