正则表达式检测c函数体的开始 [英] Regex to detect begining of the c function body
问题描述
我正在研究一个perl脚本,该脚本从c源文件打印所需的函数体.我已经写了一个正则表达式来作为函数体的开头
I working on a perl script that prints the required function body from the c source file. i have written a regex to get to the start of the function body as
(/(void|int)\s*($function_name)\s*\(.*?\)\s*{/s
但这仅适用于返回void或int(基本类型)的函数 我如何更改此正则表达式以处理用户定义的数据类型(结构或指针)
but this works only for functions returning void or int(basic types) how can i change this regex to handle user defined datatypes (struct or pointers)
推荐答案
尝试此操作(未经测试!),尽管它确实希望函数从行的开头开始:
Try this one (untested!), although it does expect the function to start at the beginning of a line :
/
^ # Start of line
\s*(?:struct\s+)[a-z0-9_]+ # return type
\s*\** # return type can be a pointer
\s*([a-z0-9_]+) # Function name
\s*\( # Opening parenthesis
(
(?:struct\s+) # Maybe we accept a struct?
\s*[a-z0-9_]+\** # Argument type
\s*(?:[a-z0-9_]+) # Argument name
\s*,? # Comma to separate the arguments
)*
\s*\) # Closing parenthesis
\s*{? # Maybe a {
\s*$ # End of the line
/mi # Close our regex and mark as case insensitive
您可以通过删除空格和注释将所有这些压缩为一行.
You can squeeze all of these into a single line by removing the whitespace and comments.
尽管使用正则表达式来解析代码通常很困难,但是这个正则表达式根本不是完美的.
Parsing code with a regex is generally hard though, and this regex is not perfect at all.
这篇关于正则表达式检测c函数体的开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!