如何使用C 中的Regex替换文件名的扩展

How do I replace the extensions of filenames using regex in c++?

本文关键字:文件名 扩展 替换 Regex 何使用 中的      更新时间:2023-10-16

我想将文件扩展名替换为 .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

当然,您可以将oldSuffixnewSuffix设置为参数,而不是静态常规。这是一个测试程序: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;

将为您更好地奏效。