ChrisInCambo
ChrisInCambo

Reputation: 8795

Regular expression to find all methods in a piece of code

I am trying to write a regular expression to match all the JavaScript method definitions in a constructor string.

//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

The regular expression should match ['myMethod_1', 'myMethod_2']. The regular expression should not match ['myMethod_3', 'myMethod_5', 'myMethod_6', 'closure'].

Here's what I have so far, but I am having problems with the ones that appear in comments:

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

I've been using this cool site to test it.

How do I solve this?

Upvotes: 1

Views: 397

Answers (3)

1800 INFORMATION
1800 INFORMATION

Reputation: 135413

One regular expression might be difficult to write and debug. Think about writing several regular expressions, one for each line that should either match to confirm or reject a piece of code.

For example,

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

and so on.

Upvotes: 0

cobbal
cobbal

Reputation: 70763

Add a ^\s* to the begining might help. It's not perfect, but it will work for your test cases.

Upvotes: 0

Andreas Petersson
Andreas Petersson

Reputation: 16518

This sounds complicated to do it correctly. You will need to create a parser for this, a simple regular expression will most likely not make it.

A very good starting point is Narcissus, which is a JavaScript parser written in ... JavaScript.

It is just 1000 lines of code. It should be possible to extract just the method-matching parts of it.

Upvotes: 5

Related Questions