Adham Atta
Adham Atta

Reputation: 350

Regex.Replace and String immutability

Say I have A Compiled Regex object :

    public static Regex myRgx = new Regex(@"[\d]+",RegexOptions.Compiled); 

Now let's say I'm reading large strings into the string variable SS , And then I use my Regex object to replace all matches within that string

    myRgx.Replace(SS,"($&)");

Question: Does .Replace internally use a StringBuilder to do the work , much like what happens in String.ReplaceAll() ?
And if it doesn't is there a way to get around this ?
Update :
I don't know if it's ok to ask another question as an update to the original question .. feel free to edit this out if it's not ok.
Question 2 : What if I need to preform a chain of replacements , Using multiple Regex objects, As in:

string input = "Some LARGE string";
input = rgx1.Replace(input,"substitution1");
input = rgx2.Replace(input,"substitution2");  
input = rgx3.Replace(input,"substitution3");  

I'm writing a morphological analyzer ,So the regex objects need to be kept separate ,And replacements need to be done in a certain order as in the code above. The number of regex objects is large and we're talking Gigabytes of text, So passing a new string object, every time a regex object is done replacing ,Isn't really an option here.
Any Suggestions?

Upvotes: 1

Views: 882

Answers (6)

Brian Wenhold
Brian Wenhold

Reputation: 349

Found a good post discussing the details of various replace methods. Performance seems to vary based on usage. For simple replaces Regex is slower but uses much less memory and creates fewer objects that require garbage collection.

Upvotes: 2

Achim
Achim

Reputation: 15702

Replace does not modify your string, but creates a new one with the requested modifications. Everything else is an implementation detail, you should not care about. If you don't trust the regex library, don't use it. Even if it behaves now as you want it to, it might change in the future without further notice.

Upvotes: 2

Gabe
Gabe

Reputation: 86718

Yes, the Regex.Replace method uses a StringBuilder, as discovered via Reflector.

Upvotes: 2

Aliostad
Aliostad

Reputation: 81660

Yes. Regex internally uses a StringBuilder so it is optimised.

Upvotes: 0

Bala R
Bala R

Reputation: 108957

Regex.Replace() does not change your string SS. it returns a brand new string with stuff replaced.

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Rest assured that the regular expression library does the right thing here. Not using a StringBuilder or something equivalent internally would doesn’t have any reasonable trade-off.

Consequently, Regex.Replace will certainly use an asymptotically efficient method here.

Upvotes: 1

Related Questions