Reputation: 1768
Think of a string like this:
public function test(data)
{
if (1 == 2)
{
alert("Wtf?");
}
switch (data)
{
case 'test':
alert("Test");
break;
}
}
I need to parse that string, so that I have the body (content) of that function.
I already got my reg exp working so that I have the contents of the function, but when there is an ending }. The regular expression stops and the content will look like this:
if (1 == 2)
{
alert("Wtf?");
I really hope somebody can help me out..
this is my Reg Exp for splitting this string:
var test = classContent.replace(/(?:(private|public)\s*)function\s*([a-zA-Z0-9_]+)\s*\(([a-zA-Z0-9_\,\s]*)\s*\)\s*{([^}]+)\}/gi, function(a, b, c, d, e) {
classMethods[c] = {
visibility : b.trim(),
params : d.trim(),
content : e.trim()
};
});
Upvotes: 1
Views: 404
Reputation: 43663
Javascript does not provide the PCRE recursive parameter (?R)
.
Check out Steve Levithan's blog, he wrote XRegExp, which replaces most of the PCRE bits that are missing. There is also a Match Recursive plugin.
Upvotes: 0
Reputation: 44259
This is generally too tough a problem for regular expressions. They cannot really handle nested structures well. Some flavors support recursive patterns, but even this would be overkill in this case. A quick fix to your given problem would be this:
/(?:(private|public)\s*)function\s*([a-zA-Z0-9_]+)\s*\(([a-zA-Z0-9_\,\s]*)\s*\)\s*{(.+)\}/gis
This allows for any characters between curly brackets (including curly brackets), and since the +
is greedy, this will go all the way to the end.
However, if your string can contain multiple functions, this will get you everthing from the first function name to the very last closing }
. And I have a feeling that this is the case for you, because you used the global modifier g
.
If this is this case (or anyway), consider using a different approach (that is, a JavaScript parser or analyzing the string yourself and counting curly brackets). Maybe this question will help you there.
Upvotes: 2