I am trying to replace the occurrences of CR(\r), LF(\n), and the combination of CR and LF as follows
- search for patter ([\r\n]+) // pattern can be '\r', '\r\r\r\n\n' '\r\n\r\n' or any combination.
- If length is 1 and character is CR, replace with LF. // pattern is '\r'
- If length is 2 and both characters are different then replace with LF. // pattern is '\r\n or \n\r'
- else replace with 2 LF. // any pattern longer than 2 characters
std::regex search_exp("([\r\n]+)");
auto replace_func = [](std::string& str_mat) -> std::string {
std::string ret = "";
if ((str_mat.length() == 1)) {
if (str_mat == "\r")
ret = "\n";
} else if (str_mat.length() == 2 && (str_mat.at(0) != str_mat.at(1))) {
ret = "\n";
} else {
ret = "\n\n";
}
return ret;
};
auto str = std::regex_replace(str, search_exp, replace_func);
But std::regex_replace does take lambda function. :(
Edit:
Example:
"\rThis is just an example\n Learning CPP \r\n Stuck at a point \r\n\n\r C++11 onwards \r\r\r\n\n"
Any suggestions?
regex_replace (str, "\n?\r|\r\n?", "\n")should perform what I just described.