Replace {x} tokens in strings

We have the URL of the template, for example:

http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId} 

and I have values ​​for these constant tokens. How to replace all these tokens with C #?

+9
c # token
Nov 29 '13 at 4:49 on
source share
5 answers

A simple approach is to use foreach and a Dictionary with String.Replace :

 var values = new Dictionary<string, string> { { "{networkid}", "WHEEE!!" } // etc. }; var url = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}"; foreach(var key in values.Keys){ url = url.Replace(key,values[key]); } 
+9
Nov 29 '13 at 5:42 on
source share

There is no standard way to "replace dictionary values" in .NET. Although there are several template engines, it is not so difficult to write a small solution for such an operation. Here is an example that works in LINQPad and uses a Regular Expression with conformance assessment .

As a result of the URL, it is the responsibility of the callers to ensure that all the values ​​provided are correctly encoded . I recommend using Uri.EscapeDataString if necessary .. but do not loop if it is being processed elsewhere.

In addition, the rules of what to do when no replacement is found should be tailored to your needs. If not found replacements should be completely excluded along with the query string key, the following can extend the regular expression to @"\w+=({\w+})" to also capture the parameter key in this particular template situation.

 string ReplaceUsingDictionary (string src, IDictionary<string, object> replacements) { return Regex.Replace(src, @"{(\w+)}", (m) => { object replacement; var key = m.Groups[1].Value; if (replacements.TryGetValue(key, out replacement)) { return Convert.ToString(replacement); } else { return m.Groups[0].Value; } }); } void Main() { var replacements = new Dictionary<string, object> { { "networkid", "WHEEE!!" } // etc. }; var src = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}"; var res = ReplaceUsingDictionary(src, replacements); // -> "http://api.example.com/sale?..&networkid=WHEEE!!&..&pageid={pageid}&.. res.Dump(); } 

More advanced methods, such as reflection and transformations, are possible, but they should be left for real template engines.

+7
Nov 29 '13 at 5:15
source share

I assume that you are trying to replace the parameters in url your values. This can be done using C # HttpUtility.ParseQueryString

Get CurrentURL from

  var _myUrl = System.Web.HttpUtility.ParseQueryString(Request.RawUrl); 

Reading a parameter from a query string

  string value1 = _myUrl ["networkid"]; 

Enter a value in the QueryString object.

  _myUrl ["networkid"] = "Your Value"; 

and then finally return it to the url

  var _yourURIBuilder= new UriBuilder(_myUrl ); _myUrl = _yourURIBuilder.ToString(); 
+5
Nov 29 '13 at 4:56 on
source share

You can use this alos using LinQ

 Dictionary<string, string> myVal = new Dictionary<string, string>(); myVal.Add("networkid", "1"); myVal.Add("pageid", "2"); myVal.Add("master", "3"); myVal.Add("optinfo", "4"); myVal.Add("publisher", "5"); myVal.Add("userId", "6"); string url = @"http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}"; myVal.Select(a => url = url.Replace(string.Concat("{", a.Key, "}"), a.Value)).ToList(); 

this line can fulfill your required functionality

myVal.Select (a => url = url.Replace (string.Concat ("{", a.Key, "}"), a.Value)). ToList ();

+2
Nov 29 '13 at 7:39
source share

There is a Nuget called StringTokenFormatter which does it well https://www.nuget.org/packages/StringTokenFormatter/

0
Nov 22 '17 at 14:27
source share



All Articles