我正在尝试使用 questions like this one设计一个正则表达式,它将匹配并给出一个函数名称和所有参数,使用非常简化的类似 Python 的语法,如下所示:
mycall(x, y, hello)
得到想要的结果:
- 函数名称:
mycall
- 参数 0:
x
- 参数 1:
y
- 参数2:
你好
当然它也应该匹配noparams()
,以及任意数量的参数。至于我的简化,我只需要参数名称,我不允许默认参数或与逗号分隔名称列表不同的东西。
我尝试使用 "(\\s*)([A-Za-z0-9_])+\\(\\)"
的变体来匹配带空格的函数名称字符串一开始就失败了,代码如下:
std::regex fnregexp(s);
std::smatch pieces_match;
if (std::regex_match(q, pieces_match, fnregexp))
{
std::cout << ">>>> '" << q << "'" << std::endl;
for (size_t i = 0; i < pieces_match.size(); ++i)
{
std::ssub_match sub_match = pieces_match[i];
std::string piece = sub_match.str();
std::cout << " submatch " << i << ": '" << piece << "'" << std::endl;
}
}
"hello()"
的输出如下:
>>>> ' hello()'
submatch 0: ' hello()'
submatch 1: ' '
submatch 2: 'o'
使用这个非常基本的语法,是否可以找到函数名称及其参数?
干杯!
最佳答案
将其用于一致性检查:
^\\s*[A-Za-z_]\\w* *\\( *(?:[A-Za-z_]\\w* *(?:, *[A-Za-z_]\\w* *)*)?\\)$
如果可以的话,使用它来提取签名的部分:
\\w+
第一个子匹配是函数名,其他是参数。
编辑:Python 的正确语法是 [A-Za-z_][A-Za-z0-9_]*
关于c++ - 用于类 python 函数参数解析的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072573/