in reply to Re^4: Parsing C Source File Functions.
in thread Parsing C Source File Functions.
First of all, unless you build a real parser, you're not going to get perfect results. But if your source code is formatted in a somewhat typical style, then you can frequently do a decent-enough job. The trick is figuring out a regular expression that captures what you want and ignores what you don't want.
So think of the difference between what the C functions look like versus what your C++ functions look like. The primary difference appears to be that your C++ functions can have colons in the name. So I'd think the first step would be to adjust the regex to allow colons in the words.
Your attempt has a bit of a problem: the chunk that gets the function name accepts either \*?: or \w+\s*. The | splits the parenthesis group into two different regexes, either of which may be satisfied. To get the colon in your identifiers, try (\*?[:\w]+\s*). Using the square brackets effectively adds the : into the word characters. After making that change, the regex will now accept things like:
Bibbity Bobbity *foo::bar (baz) {
Which is roughly where you wanted to get to. Keep in mind, though that C++ type declarations can be tricky, so you may have to adjust other parts of your regex too. Things to consider:
And these are only the ones I can think of off the top of my head. I'm sure there are other complexities that I haven't even thought of. (Afterthought: Such as templates!)
$ cat 1070117.pl #!/usr/bin/perl use strict; use warnings; my $regex = qr/(.*?)\n((?:\w+\*?\s+)+)(\*?[:\w]+\s*)\s*\((.*?)\)(\s*\{ +)/; my $text = "foo\nfizzy bar::baz(a b) {\nblarf\n"; if ($text =~ $regex) { print "Matched! $1, $2, $3\n"; } $ perl 1070117.pl Matched! foo, fizzy , bar::baz
If you're having trouble with regular expressions, then try installing YAPE::Regex::Explain and using it to explain your regular expressions. That can help you pinpoint where you're going astray. I don't use it very often (primarily because I keep forgetting that it exists!) but I find it handy when I remember about it.
...roboticus
When your only tool is a hammer, all problems look like your thumb.
|
|---|