如何在C或C ++中使用正则表达式从函数定义字符串中获取函数名称?

时间:2018-12-09 20:53:12

标签: c++ regex

我想从给定的文本中找到字符串。我的正则表达式不起作用。我不确定我做错了什么。有人可以帮我吗。

我期望输出为:myFunction

#include <iostream>
#include <string>
#include <regex>
#include <iterator>
using namespace std;

int main()
{

// Target sequence
std::string s = "function myFunction(p1, p2) { return p1 * p2; }";

// An object of regex for pattern to be searched
regex r("/^function\\s+([\\w\\$]+)\\s*\\(/");

// flag type for determining the matching behavior
// here it is for matches on 'string' objects
smatch m;

// regex_search() for searching the regex pattern
// 'r' in the string 's'. 'm' is flag for determining
// matching behavior.
regex_search(s, m, r);

// for each loop
for (auto x : m)
    cout << x << " ";
}

1 个答案:

答案 0 :(得分:0)

您用于regex的字符串不正确。您不需要在开头和结尾使用两个/字符。使用:

regex r("^function\\s+([\\w\\$]+)\\s*\\(");
//       ^ No /                         ^ No /

查看它在https://ideone.com/bLavL0上的运行情况。