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

标签 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(Clang 6.1(Apple),64 位)的 Qt Creator 3.6.0

---编辑----

我尝试这样做:

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

但是我收到一条错误消息

Use of undeclared identifier 'R'

我已经有 #include <regex>但我还需要添加其他内容吗?

最佳答案

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

转义:

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

原始字符串:

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

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

#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

关于c++ - C++ 中的正则表达式和双反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36345626/

相关文章:

python - 在字符串中查找最重复(不是最常见)序列的算法(又名串联重复)

regex - 使用 htaccess 从 url 中删除 .php

c++ - Qt Creator 无法识别 pro 中的 my 更改。文件

c++ - 在控制台应用程序的 QtCreator 中强制输出

c++ - 复制构造函数调用析构函数 C++

c++ - 如何修复 Turbo C++ 错误 "Cannot open include file: graphics.h: no such files or director"

C++ OpenMP 关键 : "one-way" locking?

JavaScript regex exec 执行时间太长

c++ - QT Creator 编译 C++ 文件?很简单的问题

c++ - Visual Studio 中的 OpenMP 任务