val val - 1 year ago 159
C++ Question

C++ can't get regex_match to work

In my code i'd like to process stirngs based on enclosing <> brackets. For this i'd like to go though the string and one by one replace the brackets and do something based on whats inside the brackets.

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.
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.
// ...

Answer Source

You need to put parenthesis () around the things you want to catch:

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;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download