0

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?

2
  • 1
    Use the Regex.Replace() method. Commented Jul 15, 2013 at 9:12
  • @AlexFilipovici I know I should use it, but I don't know the patterns needed, and how to get the key from the input string. Commented Jul 15, 2013 at 9:15

2 Answers 2

3

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];
        });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

the pattern should be \$\(.*?\) - otherwise the match for .* is greedy and there are going to be problems for cases with 2 or more possible matches.
Thanks, that worked fine, but the key should not include the $() characters, Thanks any way :)
You are welcome. It was a little bit unclear in the OP how the keys in the dictionary would look like... I updated my answer with the proper replacement code.
2

a thing like this perhaps:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.