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