What is returned in std :: smatch and how should you use it?

string "I am 5 years old"

regex "(?!am )\d"

if you go to http://regexr.com/ and apply the regex to the string you get 5. I would like to get this result using std :: regex, but I don't understand how to use the match results, and maybe also need to change the regex.

std::regex expression("(?!am )\\d");
std::smatch match;
std::string what("I am 5 years old.");
if (regex_search(what, match, expression))
{
     //???
}

      

+3


source to share


1 answer


You need to use a capture mechanism as it std::regex

doesn't support lookbehind. You used a lookahead, which checks for text that immediately follows the current location, and the regex you have doesn't do what you think.

So use the following code :

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main() {
    std::regex expression(R"(am\s+(\d+))");
    std::smatch match;
    std::string what("I am 5 years old.");
    if (regex_search(what, match, expression))
    {
         cout << match.str(1) << endl;
    }
    return 0;
}

      



Here's the template am\s+(\d+)"

. This is a mapping am

, 1+ spaces, and then fixes 1 or more digits with (\d+)

. Internally, the code match.str(1)

allows access to values ​​that are captured using capture groups. Since there is only one (...)

, one capturing group in the template , its ID is 1. Thus, it str(1)

returns the text captured in this group.

The source string literal ( R"(...)"

) allows the use of a single backslash screens for regular expressions (e.g. \d

, \s

etc).

+2


source







All Articles