如何在C++中将字符串替换为"Match case"和"Match whole word"

how to replace strings with "Match case" and "Match whole word" in C++

本文关键字:Match case word whole 替换 C++ 字符串      更新时间:2023-10-16

>我使用这个函数来替换整个文件中的字符串。

我需要搜索和替换区分大小写但问题是"匹配大小写"在此函数中不起作用,尽管代码中包含 icase 标志

int Replace() {
auto from = R"DELIM(bisb)DELIM"; //replace only "is" not "Is" or "iS" or "IS"
auto to   = "was"; //replace with "was"
 //The file is created automatically in the debug folder of the software then you 
 //can put all your "is" "Is" "iS" "IS" options into it In order to check if it works
 for (auto filename : { "A.txt" }) {
 ifstream infile{ filename };  string c { ist {infile}, ist{} };  infile.close();
 ofstream outfile{ filename };
 //std::regex::icase flag does not work    
 regex_replace(ost{outfile},begin(c),end(c),std::regex {from, std::regex::icase}, to); 
}return 0;}

如何使搜索和替换过程区分大小写?

首先,您必须出示MCVE。您的 for 循环,文件名不是描述您的问题所必需的。

匹配案例,传递std::regex::icase标志

匹配整个单词,在正则表达式周围使用b单词边界。

例:

int main()
{
    std::string input = "My name is isha. Is it true?";
    std::regex reg{R"DELIM(bisb)DELIM", std::regex::icase};
    std::cout << std::regex_replace(input, reg, "was");
    return 0;
}

输出:

My name was isha. was it true?
相关文章: