c++ - 如何创建不区分大小写的正则表达式来匹配文件扩展名?

标签 c++ regex c++11

我正在尝试匹配扩展名为 .nef 的所有文件 - 匹配必须不区分大小写。

regex e("(.*)(\\.NEF)",ECMAScript|icase);
...
if (regex_match ( fn1, e )){
    //Do Something
}

这里fn1是一个带有文件名的字符串。

但是,这仅对具有 .NEF(大写)扩展名的文件“起作用”。 .nef 扩展名将被忽略。

我也尝试过 -

regex e("(.*)(\\.[Nn][Ee][Ff])");

regex e("(.*)(\\.[N|n][E|e][F|f])");

这两者都会导致运行时错误。

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

我的代码是使用 - 编译的

g++ nefread.cpp -o nefread -lraw_r -lpthread -pthread -std=c++11 -O3

我做错了什么?这是我的基本代码。我想扩展它以匹配更多文件扩展名 .nef.raw.cr2 等。

最佳答案

您的原始表达式是正确的,应该会产生所需的结果。问题在于 <regex> 的 gcc 实现,已损坏。 This answer解释了为什么会这样的历史原因,并且还说 gcc4.9 将附带一个可用的 <regex>执行。

您的代码可以使用 Boost.Regex 运行

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main()
{
    // Simple regular expression matching
    boost::regex expr(R"((.*)\.(nef))", boost::regex_constants::ECMAScript |
                                        boost::regex_constants::icase);
    //                ^^^           ^^
    // no need escape the '\' if you use raw string literals
    boost::cmatch m;

    for (auto const& fname : {"foo.nef", "bar.NeF", "baz.NEF"}) {
        if(boost::regex_match(fname, m, expr)) {
            std::cout << "matched: " << m[0] << '\n';
            std::cout << "         " << m[1] << '\n';
            std::cout << "         " << m[2] << '\n';
        }
    }
}

Live demo

关于c++ - 如何创建不区分大小写的正则表达式来匹配文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21396611/

相关文章:

java - 正则表达式表示符号或什么都没有

regex - 如何用逗号替换文本 [Windows 上的 Linux]

c++ - 怎么会?特征中未检测到别名

c++ - 使用 C++ 导航 XAML 页面

c++ - 使用 operator new 进行内存分配并使用数据进行初始化

c++ - 如何使用 std:move 和 back inserter 将 std::list 中的元素 move 到末尾?

javascript - 验证输入的浮点格式

c++ - 虚继承的内部机制

c++ - OLE/COM 对象查看器报告 STG_E_FILENOTFOUND

c++ - C和C++中的main有什么区别