开发者

Regular expressions to find class declarations in C++ code

I need a regular expression for finding class declarations so开发者_StackOverflow社区 I can add a #define before the "class" keyword. The regular expression doesn't have to be perfect, just good enough that it catches most of the cases.


/.*class\s+([^{]+)\s*[:]?([^{]+){/

This should work for most class definitions, including template classes. The class name is captured in $1 and if it is a derived class, the base will be in $2.


How about:

/^\s*class\s/

That should work reasonably well. I'm not quite sure.


/class\s+([^\s]+)/

This will capture the class name as $1 (or the equivalent in whatever regex framework you're using). This will not work for template classes that may have spaces inside the <> that follows the class name. Parsing that is something not doable with a regular expression, since it requires matching balanced pairs of angle brackets.


Yannick's answer mostly covers it but it unfortunately also matches forward declarations (and subsequent text below them) and strict enums i.e. enum class myStrictEnum { // stuff };

This works well and is strict enough, but is arguably more verbose than it need be.

^(?!enum).*class\b\s\b[A-Za-z_][A-Za-z_0-9]*\b\s*($)?(|:\s*($)?(public|private|protected)\s*($)?\b[^{]*\s*)\s*($)?{
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜