regex_replace multipe occurence

Flaviu_ 1,031 Reputation points
2023-07-02T06:45:51.9633333+00:00

I have the following code which works:

	std::wstring data = std::regex_replace(str, std::wregex(L"a"), L"+");
	data = std::regex_replace(data, std::wregex(L"b"), L"*");

Is there possible to replace those two chars at once, with a single regex_replace call ?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,834 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 119.2K Reputation points
    2023-07-03T09:26:17.9233333+00:00

    If you are interested in a single scan of input string, then try one of approaches:

    using namespace std;
    
    wregex regex( L"(a)|(b)|$" );
    
    wcregex_iterator results_begin( str.c_str( ), str.c_str( ) + str.length( ), regex );
    wcregex_iterator results_end{};
    
    wstring data;
    
    for( auto i = results_begin; i != results_end; ++i )
    {
        const wcmatch& match = *i;
    
        data += match.prefix( ).str() + ( match[1].matched ? L"+" : match[2].matched ? L"*" : L"" );
    }
    

    or

    for( auto i = results_begin; i != results_end; ++i )
    {
        const wcmatch& match = *i;
    
        if( match[1].matched ) data += match.format( L"$`+" );
        else if( match[2].matched ) data += match.format( L"$`*" );
    }
    

    It is also possible to use for_each or transform.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Minxin Yu 12,506 Reputation points Microsoft Vendor
    2023-07-03T02:50:22.6933333+00:00

    Hi,
    Currently, std::regex_replace does not support lambda like C#. It's hard to achieve what you want.

    C#:

            string modifiedStr = Regex.Replace(str, "[ab]", match => {
                if (match.Value == "a")
                {
                    return "+";
                }
                else if (match.Value == "b")
                {
                    return "*";
                }
                return match.Value;
            });
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.