串 "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))
{
//???
}
Run Code Online (Sandbox Code Playgroud)
您需要在此处使用捕获机制,因为std::regex它不支持后视。您使用了一个前瞻性命令来检查紧随当前位置之后的文本,而您所拥有的正则表达式并没有按照您的想象做。
因此,使用以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
在这里,模式是am\s+(\d+)"。它匹配am1个空格,然后使用捕获 1个或多个数字(\d+)。在代码内部,match.str(1)允许访问使用捕获组捕获的值。由于(...)模式中只有一个,所以是 一个捕获组,其ID为1。因此,str(1)将捕获的文本返回到该组中。
原始字符串文字(R"(...)")允许使用单个反斜杠正则表达式逃逸(如\d,\s等)。