1

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?

1
  • 2
    It'd have to be a pretty darn big string to worry about the internal performance implications of a well-used framework function. Commented Apr 19, 2011 at 18:13

6 Answers 6

2

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

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

Comments

2

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

Comments

2

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.

Comments

2

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.

Comments

1

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.

Comments

0

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

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.