2009-03-19 18 views
1

コンストラクタ文字列内のすべての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']と一致しないはずです。

は、ここで私がこれまで持っているものだが、私は、コメントに表示されるものと問題があります:私はこのクールなsiteを使用してきた

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

それをテストします。

どうすれば解決できますか?

答えて

5

これは正しく行うには複雑です。このためにパーサーを作成する必要があります。シンプルな正規表現ではほとんど作成できません。

A very good starting point is NarcissusこれはJavaScriptパーサで書かれています... JavaScript。

これは、わずか1000行のコードです。メソッド一致部分だけを抽出することが可能でなければなりません。

0

^\s*を最初に追加すると役立ちます。完璧ではありませんが、テストケースではうまくいくでしょう。

0

1つの正規表現は、書き込みおよびデバッグが難しい場合があります。コードを確認または拒否するために一致する必要がある行ごとに1つずつ、いくつかの正規表現を書くことを考えてみましょう。上

例えば、

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

など。

関連する問題