4

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

4
  • 2
    Why do you need regex? Commented Nov 2, 2018 at 5: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. Commented Nov 2, 2018 at 5: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. Commented Nov 2, 2018 at 5: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: stackoverflow.com/questions/22617209/… Commented Nov 2, 2018 at 5:11

2 Answers 2

1

As halfelf mentioned in their comment, you can use boost. But you do not need to use a callback. The syntax you've given in your question will work when simply replacing std:: with boost::.

I.e., doing:

string s = "ABC";
cout << boost::regex_replace(s, boost::regex("(\\w)"), "\\L$1") << endl;

gives:

abc
Sign up to request clarification or add additional context in comments.

Comments

0

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.