Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c# - Regex replacements inside a StringBuilder

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 -

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...