C++无法regex_match工作

C++ can't get regex_match to work

本文关键字:match 工作 regex 无法 C++      更新时间:2023-10-16

在我的代码中,我想处理基于<>括号的字符串。对于这个,我想遍历字符串,一个接一个地替换括号,并根据括号内的内容做一些事情。

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>