How to find the index of the first character in a matching regex?

Viewed 114

This is my first question here, I hope that It doesn't sound stupid. So I'm trying to find a way to get the index of the first character from a string that matches the regular expression. I made my research in the regex reference in cplusplus.com but I wasn't able to find anything (probably my fault). For anyone that still don't understand what I want to do, let's make a small example, I have the following code:

int main () {
  auto re = regex("(\\d+)");
  smatch rematch;
  string str("The num is: 123481");
  regex_search(str, rematch, re);

  if (rematch.size() > 0)
    cout << "It matches!!!\n";
  else
    cout << "It doesn't match!!!\n";
}

The following example will match the number in the str string. I want to get the index that this match appears. How can I do that?

1 Answers

What you are looking for is the position() function of match_results, so something like that should work:

if (rematch.size() > 0)
    cout << "It matches at position " << rematch.position() << "\n";
Related