Reputation: 742
This code does not works, why?
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();
Display 0 !!
How I can get result[0] and result1 ("not-found", "No such file or directory")?
Test on regex101
Upvotes: 0
Views: 58
Reputation: 477640
Use std::regex_search
to find substrings that match your pattern. You also need to escape the backslashes properly, or even better, use raw string literals. The following works:
#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'; }
}
Upvotes: 2