Regex \ w escaping in C ++ 11
This code returns nothing, I am avoiding the w character in the wrong way
http://liveworkspace.org/code/3bRWOJ $ 38
#include <iostream>
#include <regex>
using namespace std;
int main()
{
const char *reg_esp = "\w"; // List of separator characters.
// this can be done using raw string literals:
// const char *reg_esp = R"([ ,.\t\n;:])";
std::regex rgx(reg_esp); // 'regex' is an instance of the template class
// 'basic_regex' with argument of type 'char'.
std::cmatch match; // 'cmatch' is an instance of the template class
// 'match_results' with argument of type 'const char *'.
const char *target = "Unseen University - Ankh-Morpork";
// Identifies all words of 'target' separated by characters of 'reg_esp'.
if (std::regex_search(target, match, rgx)) {
// If words separated by specified characters are present.
const size_t n = match.size();
for (size_t a = 0; a < n; a++) {
std::string str (match[a].first, match[a].second);
std::cout << str << "\n";
}
}
return 0;
}
+2
source to share
2 answers
As @DanielFrey said, for a normal string literal, you need to double the backslash. Since C ++ 11, a string literal: can be used instead R"(\w)"
. "R" disables special character handling, so the backslash is just a backslash. The parentheses indicate the beginning and end of a string literal and are not part of the text.
+4
source to share