python 正则表达函数_在python中使用正则表达式确定C ++函数及其参数

So I'm doing something wrong in this python script, but it's becoming convoluted and I'm losing sight of what I'm doing wrong.

I want a script to go through a file, find all the function definitions, and then pull out the name, return type, and parameters of the function, and output a "doxygen" style comment like this:

/******************************************************************************/

/*!

\brief

Main function for the file

\return

The exit code for the program

*/

/******************************************************************************/

But I'm doing something wrong with the regular expression in trying to parse the parameters... Here is the script so far:

import re

import sys

f = open(sys.argv[1])

functions = []

for line in f:

match = re.search(r'([\w]+)\s+([\S]+)\(([\w+\s+\w+])+\)',line)

if line.find("\\fn") < 0:

if match:

returntype = match.group(1)

funcname = match.group(2)

print '/********************************************************************'

print " \\fn " + match.group()

print ''

print ' \\brief'

print ' Function description for ' + funcname

print ''

if len(match.groups()) > 2:

params = []

count = len(match.groups()) - 2

while count > 0:

matchingstring = match.group(count + 2)

if matchingstring.find("void") < 0:

params.append(matchingstring)

count -= 1

for parameter in params:

print " \\param " + parameter

print ' Description of ' + parameter

print ''

print ' \\return'

print ' ' + returntype

print '********************************************************************/'

print ''

Any help would be appreciated. Thanks

解决方案

The grammar of C++ is far too complex to be handled by simple

regular expressions. You'll need at least a minimal parser.

I've found that for restricted cases, where I'm not concerned

with C++ in general, but only my own style, I can often get away

with a flex based tokenizer and a simple state machine. This

will fail in many cases of legal C++—for starters, of

course, if someone uses the pre-processor to modify the syntax;

but also because < can have different meanings, depending on

what precedes it names a template or not. But it's often

adequate for a specific job.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值