gpt4 book ai didi

c++ - 正则表达式可以,但不起作用

转载 作者:行者123 更新时间:2023-11-28 02:26:41 25 4
gpt4 key购买 nike

这段代码不起作用,为什么?

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 ("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.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'; }
}

关于c++ - 正则表达式可以,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com