C++ 正则表达式在C++;和双反斜杠

C++ 正则表达式在C++;和双反斜杠,c++,regex,qt-creator,backslash,C++,Regex,Qt Creator,Backslash,我正在读一个文本文件,格式是 People list [Jane] Female 31 ... 对于每一行,我想循环查找包含“[…]”的行 例如,[简] 我想出了正则表达式 “(^[\w+]$)” 我使用regex101.com测试了它的工作原理。 然而,当我试图在代码中使用它时,它与任何东西都不匹配。 这是我的密码: void Jane::JaneProfile() { // read each line, for each [title], add the next lines i

我正在读一个文本文件,格式是

People list
[Jane]
Female
31
...
对于每一行,我想循环查找包含“[…]”的行 例如,[简]

我想出了正则表达式

“(^[\w+]$)”

我使用regex101.com测试了它的工作原理。 然而,当我试图在代码中使用它时,它与任何东西都不匹配。 这是我的密码:

void Jane::JaneProfile() {
    // read each line, for each [title], add the next lines into its array
    std::smatch matches;
    for(int i = 0; i < m_numberOfLines; i++) { // #lines in text file
        std::regex pat ("(^\[\w+\]$)");
        if(regex_search(m_lines.at(i), matches, pat)) {
            std::cout << "smatch " << matches.str(0) << std::endl;
            std::cout << "smatch.size() = " << matches.size() << std::endl;

        } else
            std::cout << "wth" << std::endl;
    }
}
但是我有一个错误,说

使用未声明的标识符“R”


我已经有了
#include
,但我还需要包括其他内容吗?

要么转义反斜杠,要么使用原始字符版本,其前缀不会出现在正则表达式中:

逃脱:

std::regex pat("^\\[\\w+\\]$");
原始字符串:

std::regex pat(R"regex(^\[\w+\]$)regex");
工作演示(改编自OPs发布代码):


也许您需要使用C++11原始文本字符串,这样就不需要转义任何内容<代码>标准::字符串str=R“(…)”所以它类似于
td::regex pat(R“(^\[\w+\]$)”啊,我试过了,但是我得到了一个错误“使用未声明的标识符'R”-你可能知道为什么吗?它是什么版本的编译器?我使用的是基于(桌面)Qt5.5.1(Clang6.1(Apple),64位)的QtCreator 3.6.0不幸的是,当我使用第一个表达式时,我似乎没有从文本文件中获得匹配;当我使用第二个表达式时,仍然会出现错误“使用未声明的标识符'R'”:(@Ceria在我的mac电脑上用apple clang进行了测试。@Ceria只是一个想法-你是在windows机器上吗?如果是这样,你的文本文件很可能是用CR/LF而不是unix上的LF来终止行。如果是这样,你需要在读取字符串时从每个字符串中删除CR…或者获得一个合适的操作系统:)@RichardHodges:问题:“clang 6.1(苹果)“此外,.@RichardHodges谢谢你!我直接复制了regex部分,它成功了!我似乎写了一些奇怪的东西。:)
std::regex pat(R"regex(^\[\w+\]$)regex");
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    auto test_data =
    "People list\n"
    "[Jane]\n"
    "Female\n"
    "31";

    // initialise test data
    std::istringstream source(test_data);
    std::string buffer;
    std::vector<std::string> lines;
    while (std::getline(source, buffer)) {
        lines.push_back(std::move(buffer));
    }

    // test the regex

    // read each line, for each [title], add the next lines into its array
    std::smatch matches;
    for(int i = 0; i < lines.size(); ++i) { // #lines in text file
        static const std::regex pat ("(^\\[\\w+\\]$)");
        if(regex_search(lines.at(i), matches, pat)) {
            std::cout << "smatch " << matches.str() << std::endl;
            std::cout << "smatch.size() = " << matches.size() << std::endl;
        } else
            std::cout << "wth" << std::endl;
    }

    return 0;
}
wth
smatch [Jane]
smatch.size() = 2
wth
wth