jeudi 11 janvier 2018

Conditionally ignore case in c++11 regular expressions

I'm trying to write a function which will allow the user to specify if they want to ignore case in a regular expression match. I've come up with a solution, but it's pretty clunky. Is there a way to conditionally set the std::regex_constants::icase flag when building the regex?

#include <string>
#include <regex>

std::string sub(std::string string, std::string match, bool ic){
  std::regex r;
  std::regex rc(match, std::regex_constants::collate);
  std::regex ric(match, std::regex_constants::icase | std::regex_constants::collate);
  if(ic){
    r = ric;
  } else {
    r = rc;
  }
  std::smatch matches;
  if(std::regex_search(string,matches, r)){
    return matches[0];
  } else {
    return "no match";
  }
}

Aucun commentaire:

Enregistrer un commentaire