在std :: smatch中返回什么,你应该如何使用它?

时间:2017-06-14 09:27:07

标签: c++ regex

字符串"I am 5 years old"

正则表达式"(?!am )\d"

如果您转到http://regexr.com/并将正则表达式应用于您将获得的字符串5。 我想用std :: regex得到这个结果,但我不明白如何使用匹配结果,并且可能还需要更改正则表达式。

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

1 个答案:

答案 0 :(得分:3)

您需要在此使用捕获机制,因为std::regex不支持背后的。您使用前瞻检查紧跟当前位置的文本,并且您拥有的正则表达式没有按照您的想法执行。

因此,请使用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;
}

此处,模式为am\s+(\d+)"。它匹配am,1 +空格,然后使用(\d+)捕获 1个或多个数字。在代码内部,match.str(1)允许使用捕获组访问捕获的值。由于模式中只有一个(...),一个捕获组,其ID为1.因此,str(1)返回捕获到该组中的文本。

原始字符串文字(R"(...)")允许对 regex转义使用单个反斜杠(如\d\s等)。