views:

74

answers:

1

I'm writing the contents of a text file to a StringBuilder and I then want to perform a number of find/replace actions on the text contained in the StringBuilder using regular expressions.

I've run into a problem as the StringBuilder replace function is not capable of accepting regular expression arguments.

I could use Regex.Replace on a normal string but I'm under the impression that this is inefficient due to the fact that two copies of the string will need to be created in memory as .net strings are immutable.

Once I've updated the text I plan to write it back to the original file.

What's the best and most efficient way to solve my problem?

EDIT

In addition to the answer(s) below, I've found the following questions that also shed some light on my problem -

+8  A: 

The best and most efficient solution for your time is to try the simplest approach first: forget the StringBuilder and just use Regex.Replace. Then find out how slow it is - it may very well be good enough. Don't forget to try the regex in both compiled and non-compiled mode.

If that isn't fast enough, consider using a StringBuilder for any replacements you can express simply, and then use Regex.Replace for the rest. You might also want to consider trying to combine replacements, reducing the number of regexes (and thus intermediate strings) used.

Jon Skeet
I’m amazed I didn’t think of this: actually run it and see, instead of speculating on what the speed would be. I’ve deleted my speculative answer accordingly.
Timwi
If the Regex.Replace was fast enough, should I give any concern at all to memory management? Am I over analysing/optimizing things by worrying about the memory over-head of creating multiple strings?
ipr101