0

I am dilemma to decide which one to use, either to use Regex.Replace or to use Regex.Matches if you have to perform some logic on each matches to generate the replaced value.

Scenario: Reading a file (which can vary in the size) and then using the Regular expression to replace the matches. replaced value for each match is different and is generated by some logic.

Approach 1: Read the complete file, then find all the matches and then I do the foreach or for loop and replace them one by one.

Approach 2: Read the complete file, then uses the Regex.Replace method with the MatchEvaluator, where MatchEvaluator function performs the logic and returns the replaced value.

There is an article I would like to link here, which somehow gives me a feeling to not use, Regex.Replace. Link: https://blogs.msdn.microsoft.com/debuggingtoolbox/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance/

Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29
bgajj412
  • 3
  • 5
  • If you have performance concerns you should implement your own solution for your unique problem. All string functions meant to work for all cases. For example if you have only lower case characters then you can implement a better search - replace algorithm then anyone else for your case. – cokceken Nov 29 '16 at 06:13
  • If your file is smaller than 1Gb, don't worry about performance (any gains will be minimal between Regex.Replace and Regex.Matches). Just go with the approach that you think is easier to implement. – Wagner DosAnjos Nov 29 '16 at 06:14

1 Answers1

0

Approach 1:

  • This would read entire file. (Check out for memory consumption.)
  • foreach loop on large data, (more time consuming.)

Approach 2:

  • This also would read entire file.
  • MatchEvaluator(pretty sure takes more time)

Approach 3:

  • Read the file line by line. MDSN Link
  • Do string.replace() as checked by the link you provided.
  • Append each result to result file at the same time.
Prajwal
  • 3,930
  • 5
  • 24
  • 50