Click here to Skip to main content
15,883,986 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more: , +
Is it possible to use std::tr1::regex_iterator to search and replace in a string ?

I know I can use std::tr1::regex_replace to replace all occurrences (or only one), but I need to replace each "pattern" that I find with something different, so I need to iterate my input string and replace on the fly.

std::string expression; // valid input string.
std::tr1::regex variableRegExpression; // valid regular expression.

std::tr1::sregex_iterator m1(
	expression.begin(), 
	expression.end(), 
	variableRegExpression);

std::tr1::sregex_iterator m2;
std::vector<std::string> tokens;
for (; m1 != m2; ++m1)
{
	std::string token = m1->str();
	// here, I want to replace token in the input string expression, but that will probably break the iterator.
}


The above code will iterate all occurrences of what I'm searching for in the string expression.

What I'd like to do would be to replace each occurrence with something else.

I was able to do that with some loops with std::tr1::regex_search and std::regex_replace, but it does not look "clean" :

std::string expression; // valid input string.
std::tr1::regex variableRegExpression; // valid regular expression.

// substitute variables.
bool found = true;
while (found)
{
	std::tr1::smatch matchResult;

	found = std::tr1::regex_search(
                expression, matchResult, variableRegExpression  );
        if ( found )
        {
                std::string newValue("Cloud1");
                // replace only first instance.
                // will change the input string.
                expression = std::tr1::regex_replace(
                        expression, variableRegExpression, newValue, 
                        std::tr1::regex_constants::format_first_only);

        }
        else
        {
                found = false;
        }
}



Question :
Is it possible to do a simple search and replace with the regex_iterator ?

Thanks

Max.
Posted
Updated 18-Sep-13 8:29am
v2

1 solution

I am no expert in using regex_iterator, but I would agree that doing the replacements on the fly will break the iterator. But how about building a separate result string by coyping from your original string up to the match position, then appending your replacement string, then moving the next copy position marker to the end of the match ...

In this manner you do not interfere with the iterator. And this method as almost as efficient as doing the replacements in-place.
 
Share this answer
 
Comments
Maximilien 18-Sep-13 18:39pm    
Ah, nice solution!!! will look into that tomorrow.
currently the solution using regex_search and regex_replace works, but I will try your idea.

Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900