[C++代码片段] 用正则表达式提取文件路径中的扩展名
在使用 C++11 之前,一直都是使用 string 的 find_last_of 来查找扩展名,有点烦琐。
可以使用系统的 PathFindExtension 来取得,但我还是更喜欢自己写的。C++11 中有了正则表达式,估计会方便点。
下面的示例代码可以取出扩展名部分(正则表达式一向看起来很晦涩):
#include <string>
#include <regex>
#include <iostream>
#include <tuple>
std::tuple<std::string, std::string> ext(const std::string& path) {
std::regex re(R"((.+?)(\.[^.]+)?)");
std::smatch results;
std::regex_match(path, results, re);
return std::make_tuple(results[1], results[2]);
}
int main() {
std::string sa[] = {
"111",
"111.txt",
"111.",
".gitignore",
"111.txt.exe",
"111.txt.exe.",
"我.txt.exe",
"我.扩展名",
"C:\\dir\\fname.ext",
"http://path/to/a.txt",
};
for(auto& s : sa) {
auto t = ext(s);
std::cout << "[" << std::get<0>(t) << "][" << std::get<1>(t) << "]" << std::endl;;
}
return 0;
}
函数一次性返回了两个值,扩展名前面的部分(base)和扩展名。
运行结果(在线运行):
[111][] [111][.txt] [111.][] [.gitignore][] [111.txt][.exe] [111.txt.exe.][] [我.txt][.exe] [我][.扩展名] [C:\dir\fname][.ext] [http://path/to/a][.txt]