正则表达式可以,但不工作

regex ok but does not works

本文关键字:工作 正则表达式      更新时间:2023-10-16

这段代码不工作,为什么?

std::cmatch result;
std::string str("trucmuch.servicen   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 !!

如何获得result[0]和result1 ("not-found", "No such file or directory")?

regex101的测试

使用std::regex_search查找与模式匹配的子字符串。您还需要正确地转义反斜杠,或者更好地使用原始字符串文字。以下作品:

#include <iostream>
#include <regex>
#include <string>
int main()
{
    std::smatch result;
    std::string str =
        "trucmuch.servicen   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'; }
}