我试图匹配所有具有扩展名的文件.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
等.
您的原始表达是正确的,应该产生所需的结果.问题在于gcc的实现<regex>
,它被破坏了.这个答案解释了为什么会这样做的历史原因,并且还说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'; } } }
现场演示