Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to perform dynamic replacing in a regular expression?

Tags:

c#

regex

c#-4.0

Is there a way to do a regex replace in C# 4.0 with a function of the text contained in the match?

In php there is something like this:

reg_replace('hello world yay','(?=')\s(?=')', randomfunction('$0'));

and it gives independent results for each match and replaces it where each match is found.

like image 404
luis Avatar asked Apr 07 '11 17:04

luis


1 Answers

See the Regex.Replace methods that have a MatchEvaluator overload. The MatchEvaluator is a method you can specify to handle each individual match and return what should be used as the replacement text for that match.

For example, this...

The cat jumped over the dog.
0:THE 1:CAT jumped over 2:THE 3:DOG.

...is the output from the following:

using System;
using System.Text.RegularExpressions;

namespace MatchEvaluatorTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "The cat jumped over the dog.";
            Console.WriteLine(text);
            Console.WriteLine(Transform(text));
        }

        static string Transform(string text)
        {
            int matchNumber = 0;

            return Regex.Replace(
                text,
                @"\b\w{3}\b",
                m => Replacement(m.Captures[0].Value, matchNumber++)
            );
        }

        static string Replacement(string s, int i)
        {
            return string.Format("{0}:{1}", i, s.ToUpper());
        }
    }
}
like image 191
Chris Schmich Avatar answered Sep 20 '22 06:09

Chris Schmich