I’m asking this partially because it is something I would find very useful, but also to understand the syntax of the answer so I can make my own, creative, better regular expressions!
So here’s the question: I want to find a function in my code and I know part of the function name, and something that is inside of the function. For example, given these functions:
Foo::bar1(Baz* baz)
{
...
doWork();
...
}
Foo::bar2()
{
...
beHappy();
...
}
Foo::hasAbar3Meat(Baz* baz1, Baz* baz2)
{
...
beSad();
...
}
I want to find any of these “bar” functions that have the word “beHappy” in them, using regular expressions. Keep in mind that these functions may call each other, and more generally, we don’t know what is in the “…”. It may even be that more than one of these functions has “beHappy” in them.
EDIT: If it is not possible due to C++ not being a regular language, please explain why, and, if possible, give a solution with it’s required restraints (such as, “there are no nested code blocks – using curly braces {} – in the code”).
Pretending that every function has correct indentation (there are no blocks of code that belong to the function and have indentation that is less or equal to indentation of function definition):
(braces around whatToFind are here only for a bit more readability). For your particular example regex will look like this:
It is better to remove the only
?sign near(\n\1\{)in order to reduce probability that it captures code that is not a function definition. Depending on code style, more restrictions can be put on the part that ends with(\n\1\{)?. Note that if you use perl (and, probably, pcre), you can write an expression that will work with any valid C++ code, but this expression won’t definitely be regular.