Search code examples
c++regexboost-regex

How does Regex work in Boost Regex C++


I am currently using Boost Regex library and am trying to get a function called arguments in C++. For instance, I have a page with HTML and there a JavaScript function called, we will call it something like

XsrfToken.setToken('54sffds');

What I currently have, which isn't working.

std::string response = request->getResponse();

boost::regex expression;

if (type == "CSRF") {
    expression = {"XsrfToken.setToken\('(.*?)'\)"};
}

boost::smatch results;

if (boost::regex_search(response, results, expression)) {
    std::cout << results[0] << " TOKEN" << std::endl;
}

Where response is the HTML web page, and expression is the regex. The conditional statement is running, therefore I think something is wrong with my regex, but I do not know.

[EDITED]

Forgot to mention that that regex was extracted from PHP and works in a PHP regex checker/debugger


Solution

  • Your mistake not in a regex syntax though the ? is redundant after *, but in C++ string constant literal: the backslash char should be escaped with backslash:

    #include <boost/regex.hpp>
    #include <iostream>
    #include <string>
    
    std::string response("XsrfToken.setToken('ABC')");
    boost::regex expression("XsrfToken.setToken\\('(.*?)'\\)");
    
    int main() {
    
        boost::smatch results;
    
        if (boost::regex_search(response, results, expression)) {
            std::cout << results[0] << " TOKEN" << std::endl;
        }
    }