gpt4 book ai didi

C++ 无法让 regex_match 工作

转载 作者:行者123 更新时间:2023-11-30 05:23:35 24 4
gpt4 key购买 nike

在我的代码中,我想根据封闭的 <> 括号处理 stirngs。为此,我想遍历字符串并一个一个地替换括号并根据括号内的内容做一些事情。

string msg = "This is an <red>Example<> message. For <blue>exampleness' sake<>.";
std::regex rexpr("<[a-zA-Z]*>");

// replace the first set of <> with %c, return the non-replaced version, and process it.
while(true){
std::smatch smatch;
// cant find any matches...
std::regex_match(msg, smatch, rexpr);
string key = smatch[0]; // this is empty from the start.

if(key.empty()) break; // no more keys, break.

// replace <...>
std::regex_replace(msg, rexpr, "%c", std::regex_constants::format_first_only);

if(key.size() == 2) continue; // closing brackets, nothing to process

// cut the brackets
key = key.substr(1, key.size() - 1);

// process the key.
// ...
}

最佳答案

你需要在你想要捕获的东西两边加上括号():

string msg = "This is an <red>Example<> message. For <blue>exampleness' sake<>.";
std::regex rexpr("(<[a-zA-Z]*>)");

smatch match;
if( regex_search(msg, match, rexpr) ) {
cout << match[0] << endl;
}

输出:

<red>

关于C++ 无法让 regex_match 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063588/

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