std::regex与工作表达式不匹配

std::regex not matching a working expression?

本文关键字:表达式 不匹配 工作 regex std      更新时间:2023-10-16

无论出于何种原因,我为程序制作的regexp都不会与任何其他实现中匹配的行匹配。我想知道是否有一些新语法我不懂?

这是我自己的实现:

std::string line, pattern("[LS] 0x[0-9a-fA-F]{8}");
std::regex rx(pattern, std::regex::basic);
uint line_count = 0;
while (getline(in_file, line))
{
    line_count++;
    if (std::regex_match(line, rx))
    {
        bool type = (line[0] == 'L');
        uint address = (uint) std::stoul(line.substr(4, 8), nullptr, 16);
        m_type_store.push_back(type);
        m_address_store.push_back(address);
    } else {
        std::cerr << line << " |" << line_count << '|' << std::endl;
        in_file.close();
        exit(1);
    }
}

每次它都无法匹配文件的第一行,这就是:

S 0x0022f5b4

我觉得这很好…我是不是错过了什么?

在代码中,您使用的是Basic正则表达式。我不确定C++,但通常在Basic RE中,当指定多重性时,需要在{}前面加上。换句话说,您的代码应该是:

std::string line, pattern("[LS] 0x[0-9a-fA-F]{8}");

或者,您可以使用扩展RE,而不是基本RE