Capturing matched text when using Regex.Replace

  • Thread starter Thread starter Kyle Blaney
  • Start date Start date
K

Kyle Blaney

How do I capture matched text when using Regex.Replace? I have
searched the newsgroup for an answer but can't find one.

For example, suppose I want to remove all digits from the beginning of
a string and print out the digits that were removed. I have several
options:

(1) Call Regex.Match and then call Regex.Replace if the match is
successful.
(2) Call Regex.Replace using a MatchEvaluator where the
MatchEvaluator stores the Match somewhere.

Both options work but the first option is inefficient as it must
search the input string twice and the second option is clumsy at best.

Is there a better way?
 
You can check out the Result() method of the Match object. You could call
the Regex.Match method, access the result of the match, and then call Result
to perform the replacement.


Brian Davis
http://www.knowdotnet.com
 
Back
Top