C ++中的正则表达式和双反斜杠

时间:2016-03-31 23:35:48

标签: 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 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;
    }
}

当我运行此代码时,所有行都转到else循环,没有任何匹配...

我搜索了答案,但是当我看到C ++你必须使用双反斜杠而不是一个反斜杠来逃避时我感到困惑...但即使我使用双反斜杠它也不适用于我的代码.. 。 我哪里出错了?

顺便说一句,我正在使用基于(桌面)Qt 5.5.1的Qt Creator 3.6.0(Clang 6.1(Apple),64位)

---编辑----

我尝试过:

std::regex pat (R"(^\[\\w+\]$)");

但我收到错误

  

使用未声明的标识符'R'

我已经有#include <regex>但是我还需要包含其他内容吗?

1 个答案:

答案 0 :(得分:1)

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

转义:

std::regex pat("^\\[\\w+\\]$");

原始字符串:

std::regex pat(R"regex(^\[\w+\]$)regex");

工作演示(改编自OPs发布的代码):

#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