Take the 2-minute tour ×

I have some existing text that I need to replace with replacement text. The replacement text to be used depends on the existing text. Here's a simple translation table that shows my problem:

    ,'A',  ==> ,'Fred',
    ,'B',  ==> ,'Mary',
    ... and so on...

It's easy enough to match the original text. The part I'm having a problem with is the replacement text. As you can see, the replacement text depends on the matched text: If ,'A', was found, I need to replace it with ,'Fred',. Basically, I seem to need a translation table mechanism.

I'm using the .NET RegEx classes.

I understand capturing matches and re-using them in the replacement text but I don't think that's going to do the trick. Are there any suggestions?

share|improve this question
I'm using the .NET RegEx classes, although I don't think that matters. --> It matters. Depending on the library, some operation are made possible. –  nhahtdh Oct 22 '12 at 16:08
I'm not familiar with the .NET RegEx implementation, but I remember solving a similar challenge with Perl RegEx embedded functions, whereby I would just replace with a custom subroutine and pass the matched string. My sub routine would handle all the rules. Perhaps there is something similar in .NET RegEx?? –  Bryan Allo Oct 22 '12 at 16:14
add comment

2 Answers

Since you're using .NET there are two approaches:

  1. Multiple replacements:

    string.Replace("A", "Fred");
    string.Replace("B", "Mary");
    // ... (could use regex based replacement if necessary)
  2. Pass a MatchEvaluator delegate to Regex.Replace instead of the replacement string:

    Regex.Replace(input, matchRegexString, match => {
      // Code that takes a System.Text.RegularExpressions.Match and returns a string

    and the return of the delegate is used as the replacement text. (There is also a non-static version where you create a Regex instance.) In the past I've done this to perform substitutions based on %key% in the input being looped up in a dictionary.

share|improve this answer
Note that option one becomes problematic if one replacement string contains another one which is search for later. (say A was replace with Bert, then due to the second line this would result in A => Maryert) –  m.buettner Oct 22 '12 at 19:00
add comment

The only way to do this without multiple replacements and without delegates/subroutines, I believe, also only works if the substitution strings already exist "later" in your subject string.

Replace this:


With this:


Yes, a rather silly trick. Voting @Richard up to apologize for the silliness.

share|improve this answer
add comment

Your Answer


