There is a method
Regex.Replace(string source, string pattern, string replacement)
The last parameter supports pattern replacements such as ${groupName} and others (but I don’t know the group name in the run-time).
In my case I have the dynamically created pattern like:
(?<c0>word1)|(?<c1>word2)|(?<c2>word3)
My purpose is to replace each group with the value depending on group name. For example, the word “word1” will be replaced with <span class="c0">word1</span>. This is for search results highlighting like google.
Is it possible to do this using the method above not using overloaded method with MatchEvaluator parameter?
Thanks in advance!
I don’t think using the ${groupname} in the manner you suggested is feasible unless I am misunderstanding the exact replacement that’s being performed. The reason is the replacement string has to be constructed in such a way that it accounts for each group name. Since they are dynamically generated this doesn’t make it possible. In other words how, in 1 statement, do you design a replacement string that would cover c0…cn and substitute their respective capture values? You could loop through the names but how would you keep the modified text intact to perform 1 replacement per groupname?
I do have a possible solution for you though. It still uses the MatchEvaluator overload, but with some lambda expressions and LINQ you can get this down to 1 line. However, I’ll format it for clarity below. Perhaps this will fit your needs or point you in the right direction.
Output: