此代码不起作用,为什么?
std::cmatch result;
std::string str("trucmuch.service\n Loaded: not-found (Reason: No such file or directory)\n Active: inactive (dead)... (101)");
std::regex rgx("Loaded:\s+(\S+)(?:\s+\((?:Reason:\s*)?([^)]*)\))?", std::regex::ECMAScript);
std::regex_match(str.c_str(), result, rgx);
qDebug() << result.size();
显示0 !!
我如何获得结果[0]和结果1(&#34;未找到&#34;,&#34;没有这样的文件或目录&#34;)
上进行测试答案 0 :(得分:2)
使用std::regex_search
查找与您的模式匹配的子字符串。您还需要正确地转义反斜杠,甚至更好地使用原始字符串文字。以下作品:
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::smatch result;
std::string str =
"trucmuch.service\n Loaded: not-found (Reason: No such file "
"or directory)\n Active: inactive (dead)... (101)";
std::regex rgx(R"(Loaded:\s+(\S+)(?:\s+\((?:Reason:\s*)?([^)]*)\))?)",
std::regex::ECMAScript);
std::regex_search(str, result, rgx);
for (const auto & sm : result) { std::cout << sm << '\n'; }
}