2

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

Community
  • 1
  • 1
user3123061
  • 757
  • 5
  • 14
  • You may get *length* of *result* match of `std::regex_match` – Jarod42 Jan 01 '14 at 12:54
  • virtually all regex search facilities will give you the matching substring if you want it (eg instead of a yes/no for match present). You can then ask the length of that string. – RichardPlunkett Jan 01 '14 at 12:59

1 Answers1

3

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.

Sebastian
  • 8,046
  • 2
  • 34
  • 58