user3123061
user3123061

Reputation: 769

How to get length of regex match with C++11 or Boost?

Is there a library function which can be used to get length of the first regular expression match (and if there is no match it returns 0)?

So i need some function principialy similar to this:

int length_of_match(const std::string& s, const std::string& rx)
{
    ...
}

Which can be easily used for example this way:

int a = length_of_match("number = 10", "^[a-zA-z][a-zA-z0-9]*");
int b = length_of_match(" = 10", "^[a-zA-z][a-zA-z0-9]*");

and after that a == 6 and b == 0

?

EDIT:

Thanks for replies, that helped me lot. Solution for my question is:

int length_of_match(const std::string& s, const std::string& rx)
{
    boost::regex expr(rx);
    boost::match_results<std::string::const_iterator> what;
    if (!regex_search(s.begin(), s.end(), what, expr)) return 0;
    return what.length();
}

Boost works great. I tried also STL regex, but i find that STL regex functionality is buggy with mingw GCC 4.7.1:

is-gcc4-7-buggy-about-regular-expressions

Upvotes: 3

Views: 1835

Answers (1)

Sebastian
Sebastian

Reputation: 8164

As in match_results boost documentation, there is: length(n) which returns the length of the specified match.

An alternative approach would be: get the matched string and return its length.

Upvotes: 3

Related Questions