user1809943
user1809943

Reputation: 141

c# wildcard search replace in a string

I am able to do a search but can't figure out how to do a replace. I have redirectFrom and redirectTo wildcard patterns setup as shown below in the code. For the given input I need the given expected value. Any help or advice will be highly appreciated. Many thanks.

using System.Text.RegularExpressions;

class Program
{
    const string redirectFrom = "/info/*";
    const string redirectTo = "/company-info/*";

    const string input = "/info/abc";
    const string expected = "/company-info/abc";

    static void Main(string[] args)
    {
        var pattern = redirectFrom.Replace("*", ".*?");
        pattern = pattern.Replace(@"\", @"\\");
        pattern = pattern.Replace(" ", @"\s");

        var regex = new Regex(pattern, RegexOptions.None);
        if (regex.IsMatch(input))
        {
            Console.WriteLine("Match");

            var replaceregex = new Regex(pattern, RegexOptions.None);
            string result = replaceregex.Replace(input, new MatchEvaluator(Program.TransformSourceUrl));

        }
        else
        {
            Console.WriteLine("No Match");
        }

        Console.ReadKey();
    }

    private static string TransformSourceUrl(Match m)
    {
        int matchCount = 0;
        while (m.Success)
        {
            Console.WriteLine("Match" + (++matchCount));
            for (int i = 1; i <= 2; i++)
            {
                Group g = m.Groups[i];
                Console.WriteLine("Group" + i + "='" + g + "'");
                CaptureCollection cc = g.Captures;
                for (int j = 0; j < cc.Count; j++)
                {
                    Capture c = cc[j];
                    System.Console.WriteLine("Capture" + j + "='" + c + "', Position=" + c.Index);
                }
            }
            m = m.NextMatch();
        }
        return "";
    }

Upvotes: 0

Views: 564

Answers (1)

BenM
BenM

Reputation: 553

Regex regex = new Regex(pattern);
string output = regex.Replace(input, replacement);

http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx

Upvotes: 1

Related Questions