3

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++?

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 1
    [Why do you need regex?](https://stackoverflow.com/q/313970/5376789) – xskxzr Nov 02 '18 at 05:08
  • As far as I know, lowercasing is exclusive to Perl-style regex. C++ doesn't have a Perl-style regex syntax option, so I'm guessing it can't. Sure, it's useful for on-the-fly changes in a text editor, but you have a string and you have algorithms that work on strings, so I don't see the point. – chris Nov 02 '18 at 05:09
  • @xskxzr, because my purpose is complex. not simplely replace all chars. some like this "I DON'T want to ...", I want to replace "DON'T", but not "I". regex can do this easily. – Zhang Nov 02 '18 at 05:10
  • 4
    AFAIK, no such magic like `\L$1` in C++. The best shot may be boost regex_replace with a lambda applying tolower() on each character. Or you can use similar technique here: https://stackoverflow.com/questions/22617209/regex-replace-with-callback-in-c11 – halfelf Nov 02 '18 at 05:11

1 Answers1

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;

}
Administrator
  • 254
  • 1
  • 8