What is the best way to replace Regex with StringBuilder?

Possible duplicate:
Replace regular expressions inside StringBuilder

What is the best way to reuse Regex Replace on a StringBuilder?

If you do not mind being a tl;dr person, read on for details:

Hi, I have a function that performs quite a lot of string operations on a string. Therefore, naturally, for this I use the StringBuilder class. Now I'm in a pretty dilemma.

My function looks something like this:

  ParsedText.Append("some footers here"); ParsedText.Replace("[b]","<b>"); //format all bold opens ParsedText.Replace("[/b]","</b>"); //format all bold closes ParsedText.Replace("\n","<br />"); //format newlines .... sh!* load of other replaces and manipulations ... //Add <a href> to all links ParsedText = new StringBuilder(Regex.Replace(ParsedText, "pattern", "replacement")) 

And now I have ... a custom list of words (patterns) that I would like to replace - about 20 patterns.

I am trying to replace all emoticon characters with appropriate images; So:

 :) becomes <img src="smile.png" /> ;) becomes <img src="wink.png" /> 

etc. I have about 20 images / characters to replace, and I use this regex

 (?<=^|\s):d(?=$|\s) //positive lookahead and lookback at :d 

which Bob Vale is kindly provided.

All this is great, except that I do not know how to replace the regular expression with StringBuilder, and I do not want to create a new StringBuilder as follows:

  ParsedText = new StringBuilder(Regex.Replace(...)); 

twenty times since I think he defeats the whole purpose of preserving memory.

So, What is the best way to make a Regex Replace on a StringBuilder?

Thanks!

+6
source share
2 answers

The easiest way to do this is to reorganize existing filters into a method that you can call to run all filters at once. Once this is done, you can change the code to start calling this method for a smaller line each time you add to the line builder before adding a new line, instead of waiting until the end and you have to build a large line several times. This is important because it can save you the trouble of having a bunch of objects along the way, and otherwise there are a lot more garbage collectors.

Once you achieve this, if you are truly ambitious, you can also overwrite to start using streams rather than string. This will allow you to combine several of your filters into a custom high-performance state machine, which should have a measurable positive effect on performance. But this last step will depend on the clarity of the code and simple maintenance, so do not do this if you do not see this code as the driving force of your application.

+3
source

See this question and advice from Jon Skeet :

The best and most effective solution for your time is to try the easiest approach first: forget StringBuilder and just use Regex.Replace.

+2
source

Source: https://habr.com/ru/post/893360/


All Articles