Let's say I have some text such as this:
[MyAppTerms.TermName1]. [MyAppTerms.TermName2]. 1- [MyAppTerms.TermNameX] 2- ...
I want to replace every occurrence of [MyAppTerms.Whatever]
with the result of ReadTerm( "MyAppTerms.Whatever" )
, where ReadTerm
is a static function which receives a term name and returns the term text for the current language.
Is this feasible using Regex.Replace
? (alternatives are welcome). I'm looking into substitution groups but I'm not sure if I can use functions with them.
Use the
Regex.Replace(String, MatchEvaluator)
overload.The pattern
\[MyAppTerms\.([^\]]+)\]
matches your[MyAppTerms.XXX]
tags and captures theXXX
in a capture group. This group is then retrieved in yourMatchEvaluator
delegate and passed to your actualReadTerm
method.It's even better with lambda expressions (since C# 3.0):
Here, you define the evaluator straight inside the code which uses it (keeping logically connected pieces of code together) while the compiler takes care of constructing that
MatchEvaluator
delegate.