Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have to check a string to various regular expressions in C++. Up to now, I've done this using something similar to this:

regex regex_a (".."); string rewrite_a = "($1/$2)";
regex regex_b (".."); string rewrite_b = "($1)";
regex regex_c (".."); string rewrite_c = "($2)";

if (regex_match(string, regex_a)) {
    cout << regex_replace(string, regex_a, rewrite_a);
} else if (regex_match(string, regex_b)) {
    cout << regex_replace(string, regex_b, rewrite_b);
} else if (regex_match(string, regex_c)) {
    cout << regex_replace(string, regex_c, rewrite_c);
} 

Is this the cleanest way to do this? Isn't there a way to make a regex array and iterate through that? It would make the code much more readable.

share|improve this question

1 Answer

up vote 2 down vote accepted

Probably like this:

C++11:

vector< pair<regex, string> > regex_pairs = { {regex(".."), "($1/$2)"}, {regex(".."), "($1)"}, {regex(".."), "($2)"} };
for(auto pa:regex_pairs){
    cout << regex_replace(string, pa.first, pa.second);
}

C++03:

vector< pair<regex, string> > regex_pairs;
regex_pairs.push_back(make_pair(regex(".."), "($1/$2)"));
regex_pairs.push_back(make_pair(regex(".."), "($1)"));
regex_pairs.push_back(make_pair(regex(".."), "($2)"));
for(vector< pair<regex, string> >::iterator it = regex_pairs.begin();it!=regex_pairs.end(); it++){
    cout << regex_replace(string, it->first, it->second);
}
share|improve this answer
Hello, and welcome to Code Review! :) I'll hope you'll enjoy it. Notes about your answer: you can use a map instead of a vector of pairs and it's important to show how you would initialize regex_pairs. – Quentin Pradet May 6 at 12:01
Yes, I should have the code to initialize regex_pairs, and just fixed it. Thanks ! Also, as you said, one can also use map as you said, if one want to sort outputs by keys. – Tsuneo Yoshioka May 6 at 12:05
This works, very nice, thanks! Way better :) (btw, in line 7 you have regel_replace which should be regex_replace) – Camil Staps May 6 at 12:17
Note: With C++11, initialization can be nicer. – Quentin Pradet May 6 at 12:31
Definitely! I updated the answer. Thanks again ! – Tsuneo Yoshioka May 6 at 19:29
show 4 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.