问题
I find this regex for replacement Regex replace uppercase with lowercase letters
Find: (\w) Replace With: \L$1
My code
string s = "ABC";
cout << std::regex_replace(s, std::regex("(\\w)"), "\\L$1") << endl;
runs in Visual Studio 2017.
output:
\LA\LB\LC
How do I write the lowercase function mark in C++?
回答1:
Since there is no the magic like \L
, we have to take a compromise - use regex_search and manually covert the uppers to lowers.
template<typename ChrT>
void RegexReplaceToLower(std::basic_string<ChrT>& s, const std::basic_regex<ChrT>& reg)
{
using string = std::basic_string<ChrT>;
using const_string_it = string::const_iterator;
std::match_results<const_string_it> m;
std::basic_stringstream<ChrT> ss;
for (const_string_it searchBegin=s.begin(); std::regex_search(searchBegin, s.cend(), m, reg);)
{
for (int i = 0; i < m.length(); i++)
{
s[m.position() + i] += ('a' - 'A');
}
searchBegin += m.position() + m.length();
}
}
void _replaceToLowerTest()
{
string sOut = "I will NOT leave the U.S.";
RegexReplaceToLower(sOut, regex("[A-Z]{2,}"));
cout << sOut << endl;
}
来源:https://stackoverflow.com/questions/53112726/how-do-i-use-stdregex-replace-to-replace-string-into-lowercase