C ++无法使regex_match正常工作

时间:2016-08-21 11:19:02

标签: c++ regex

在我的代码中,我想基于封闭<>来处理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.
    // ... 
}

1 个答案:

答案 0 :(得分:1)

您需要将括号()放在要捕获的内容周围:

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>