C++ 正则表达式\w在C+中转义+;11

C++ 正则表达式\w在C+中转义+;11,c++,regex,c++11,C++,Regex,C++11,此代码没有返回任何内容,我是否以错误的方式转义了w字符 38美元 #包括 #包括 使用名称空间std; int main() { const char*reg_esp=“\w”//分隔符列表。 //这可以使用原始字符串文字来完成: //常量字符*reg_esp=R“([,。\t\n;:]); std::regex rgx(reg_esp);/“regex”是模板类的一个实例 //参数类型为“char”的“basic_regex”。 std::cmatch match;//“cmatch”是模板类

此代码没有返回任何内容,我是否以错误的方式转义了w字符

38美元

#包括
#包括
使用名称空间std;
int main()
{
const char*reg_esp=“\w”//分隔符列表。
//这可以使用原始字符串文字来完成:
//常量字符*reg_esp=R“([,。\t\n;:]);
std::regex rgx(reg_esp);/“regex”是模板类的一个实例
//参数类型为“char”的“basic_regex”。
std::cmatch match;//“cmatch”是模板类的一个实例
//“match_results”与类型为“const char*”的参数匹配。
const char*target=“看不见的大学-Ankh Morpock”;
//标识由“reg_esp”字符分隔的“target”的所有单词。
if(std::regex_搜索(目标、匹配、rgx)){
//如果存在由指定字符分隔的单词。
const size_t n=match.size();
对于(大小a=0;aSTD::CUT< P>正则表达式应该包含<代码> \W/COD>,由两个字符组成:<代码> \//>代码> <代码> W/COD>,因此您的C++源代码应该包含<代码> \\w”。
因为您需要转义反斜杠。

正如@DanielFrey所说,对于普通字符串文字,您必须将反斜杠加倍。对于C++11,您可以使用原始字符串文字:
R”(\w)
。“R”关闭特殊字符的处理,因此反斜杠只是一个反斜杠。括号标记原始字符串文字的开头和结尾,不属于文本的一部分。

@johnypaulling如果它不断向您抛出异常:您需要使用支持上述
的编译器和标准库不适用于libstdc++。它确实适用于Clang和libc++,在我的系统上,我需要将
-stdlib=libc++
添加到
Clang++
@JohnnyPauling的命令行中。我认为LWS没有libc++可用,它似乎使用libstdc++,因此当您尝试使用正则表达式时,它总是会抛出异常。现在这段代码在LWS with clang-3.2&libc++:@niXman噢,太好了!(我以前自己试过,但一定是弄错了,可能是我太匆忙了,试过了
-stdlib=c++
,或者其他同样令人尴尬的东西;)你也需要帕伦,至少;
R”(\w)
#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;
}