-1

In c++11, if I want to match all txt files starting with only lower characters e.g. [a-z]+\.txt writing in regular expression syntax, why do I have to use double escape which is

std::regex txt_regex("[a-z]+\\.txt");

Is there any special meaning for \. in C++?

cigien
  • 57,834
  • 11
  • 73
  • 112

1 Answers1

3

No, there is no special meaning for \. in c++. However, there is a special meaning for \, which is an escape sequence in c++ (the same as for a regex). So you need to escape the . so that the regex treats it as a literal .. Then you need another \ for c++ itself, to escape the \.

You can avoid the escape for c++, by using raw-string-literals, like this:

std::regex txt_regex(R"([a-z]+\.txt)");
                           // ^ only the escape for . is needed
cigien
  • 57,834
  • 11
  • 73
  • 112