如何在C ++中将字符串替换为“匹配大小写”和“匹配整个单词”

时间:2019-01-23 17:48:14

标签: c++

我使用此功能替换整个文件中的字符串。

我需要搜索并替换以区分大小写 但问题是尽管代码中包含icase标志,但“匹配大小写”在此功能中不起作用

int Replace() {

auto from = R"DELIM(\bis\b)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;}

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

1 个答案:

答案 0 :(得分:1)

首先,您必须出示MCVE。您的for循环中,不需要使用文件名来描述您的问题。

对于

匹配大小写,通过std::regex::icase标志

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

示例:

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

输出:

My name was isha. was it true?