Abdallah Nasir
Abdallah Nasir

Reputation: 631

Replace value dynamically with regular expression

I have a url like

http://www.somesite.com/$(someKey).php

I have a dictionary includes these keys, what I need is using the Regex to replace the $(*) with the value in the dictionary labeled with that key.

How can I do that?

Upvotes: 0

Views: 122

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32571

You may use the Regex.Replace Method. Try this:

class Program
{
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, string>();
        dict.Add("someKey1", "MyPage1");
        dict.Add("someKey2", "MyPage2");

        var input = "http://www.somesite.com/$(someKey2).php";
        var output = Regex.Replace(input, @"\$\((.*?)\)", m => 
        {
            return dict[m.Groups[1].Value];
        });
    }
}

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

a thing like this perhaps:

url = Regex.Replace(url , @"\$\(([^)]+)\)", delegate(Match m){ return dict[m.Groups[1]]; });

Upvotes: 2

Related Questions