-1

I want to find string from given text. My regular expression is not working. i am not sure what i did mistake. Can some one help me please.

I am expecting ouput as : 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 << " ";
}
uv_
  • 746
  • 2
  • 13
  • 25
  • 1
    C++ function declaration syntax is too complex to be properly parsed with regex. – πάντα ῥεῖ Dec 09 '18 at 20:55
  • 2
    @πάνταῥεῖ They don't seem to be parsing a C++ declaration, it starts with `function` instead of a return type. OP: What language are you trying to parse? –  Dec 09 '18 at 20:58
  • 1
    Possible duplicate of [Regex for extracting functions from c++ code](https://stackoverflow.com/questions/28833465/regex-for-extracting-functions-from-c-code) – Dmytro Dadyka Dec 09 '18 at 21:01

1 Answers1

0

The string you are using for the regex is not correct. You don't need the two / characters at the start and the end. Use:

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

See it working at https://ideone.com/bLavL0.

R Sahu
  • 204,454
  • 14
  • 159
  • 270