如何使用C 中的Regex替换文件名的扩展
How do I replace the extensions of filenames using regex in c++?
我想将文件扩展名替换为 .nef
到 .bmp
。我该如何使用Regex?
我的代码像 -
string str("abc.NEF");
regex e("(.*)(\.)(N|n)(E|e)(F|f)");
string st2 = regex_replace(str, e, "$1");
cout<<regex_match (str,e)<<"REX:"<<st2<<endl;
regex_match (str,e)
让我受到打击,但st2
结果空白。我对Regex并不熟悉,但我希望st2
中会出现一些东西。我做错了什么?
尝试这个。
它将匹配.nef或.nef
string str("abc.NEF");
regex e(".*(.(NEF)|.(nef))");
string st2 = regex_replace(str,e,"$1");
$ 1将捕获.NEF or .nef
在此处检查
尝试此
string test = "abc.NEF";
regex reg(".(nef|NEF)");
test = regex_replace(test, reg, "your_string");
我建议不要将Regex用于如此简单的任务。尝试此功能:
#include <string>
#include <algorithm>
std::string Rename(const std::string& name){
std::string newName(name);
static const std::string oldSuffix = "nef";
static const std::string newSuffix = "bmp";
auto dotPos = newName.rfind('.');
if (dotPos == newName.size() - oldSuffix.size() - 1){
auto suffix = newName.substr(dotPos + 1);
std::transform(suffix.begin(), suffix.end(), suffix.begin(), ::tolower);
if (suffix == oldSuffix)
newName.replace(dotPos + 1, std::string::npos, newSuffix);
}
return newName;
}
首先,我们找到一个定界符位置,然后获取整个文件扩展名(suffix
),将其转换为较低的情况并比较oldSuffix
。
当然,您可以将oldSuffix
和newSuffix
设置为参数,而不是静态常规。这是一个测试程序:http://ideone.com/d09nvl
我认为Boost提供了最简单,最可读的解决方案
auto result = boost::algorithm::ireplace_last_copy(input, ".nef", ".bmp");
我认为这
string str("abc.NEF");
regex e("(.*)\.[Nn][Ee][Ff]$");
string st2 = regex_replace(str, e, "$1.bmp");
cout<<regex_match(str, e)<<"REX:"<<st2<<endl;
将为您更好地奏效。
相关文章:
- 从命令行c++发送文本文件名
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 是否可以通过C++扩展强制多个python进程共享同一内存
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 扩展光电二极管探测器以支持多个传感器
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- C++中的VLA,扩展名为std=C++11
- OpenGL 和 GLM 矩阵无法正确扩展,总是按比例缩小
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++返回 Numpy 数组的 Python 扩展模块
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 扩展可变参数模板中的变量名称
- 运行正则表达式时未选中的异常 - 从文件路径获取不带扩展名的文件名
- 如何使用C 中的Regex替换文件名的扩展
- 如何在虚幻引擎中获取不带扩展名的文件名
- 带有可选扩展名的c++ 11正则表达式捕获文件名
- 如何在GNU Makefile中只获取文件名而不扩展名
- 从文件名中删除扩展名的简单方法
- 如何从文本文件中提取扩展名为.txt的文件名