-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 << " ";
}
3
  • 1
    C++ function declaration syntax is too complex to be properly parsed with regex. Commented Dec 9, 2018 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? Commented Dec 9, 2018 at 20:58
  • 1
    Possible duplicate of Regex for extracting functions from c++ code Commented Dec 9, 2018 at 21:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.