Std :: regex escape backslash in file path

I am creating a line std::regex(__FILE__)as part of a unit test that checks the output of an exception that prints the file name.

On Windows, this fails:

regex_error (error_escape): expression contains an invalid escaped character or trailing escape code.

since the extension macro __FILE__contains non-exclusive backslashes.

Is there a more elegant way to avoid backslashes than looping through the resulting string (i.e. using an algorithm stdor some function std::string)?

+4
source share
3 answers

, . .

, C:\Program Files (x86)\Vendor\Product\app.exe, . ( ), , ().

, :

std::string EscapeForRegularExpression(const std::string &s) {
  static const std::regex metacharacters(R"([\.\^\$\-\+\(\)\[\]\{\}\|\?\*)");
  return std::regex_replace(s, metacharacters, "\\$&");
}

( * ?, , .)

" ", , :

std::string EscapeForRegularExpression(const std::string &s) {
  static const char metacharacters[] = R"(\.^$-+()[]{}|?*)";
  std::string out;
  out.reserve(s.size());
  for (auto ch : s) {
    if (std::strchr(metacharacters, ch))
      out.push_back('\\');
    out.push_back(ch);
  }
  return out;
}

, , metacharacters, .

+1

@AdrianMcCarthy .


, , - , :

std::string escapeBackslashes(const std::string& s)
{
    std::string out;

    for (auto c : s)
    {
        out += c; 
        if (c == '\\') 
            out += c;
    }

    return out;
}

std::regex(escapeBackslashes(__FILE__));

It O(N), , , , , , , .

+1

polymapper.

, , , " ".

, , " " . , , / " ".

template<class Op>
auto polymapper( Op&& op ) {
  return [op=std::forward<Op>(op)](auto&& r) {
    using std::begin;
    using R=std::decay_t<decltype(r)>;
    using iterator = decltype( begin(r) );
    using T = typename std::iterator_traits<iterator>::value_type;
    std::vector<T> data;
    for (auto&& e:decltype(r)(r)) {
      for (auto&& out:op(e)) {
        data.push_back(out);
      }
    }
    return R{ data.begin(), data.end() };
  };
}

escape_stuff:

auto escape_stuff = polymapper([](char c)->std::vector<char> {
  if (c != '\\') return {c};
  else return {c,c};
});

.

int main() {
  std::cout << escape_stuff(std::string(__FILE__)) << "\n";
}

, . , , .

, polyapper , . ( , ).

+1

Source: https://habr.com/ru/post/1653005/


All Articles