开发者

How do I use a regex to replace an Id in the middle of a Url?

开发者 https://www.devze.com 2023-01-29 16:10 出处:网络
I need a Regex or any other solution to replace an id in the middle of a Url (not in querystring). Url example:

I need a Regex or any other solution to replace an id in the middle of a Url (not in querystring).

Url example:

http://localhost:1876/category/6?sortBy=asc&orderBy=Popular

I开发者_Go百科 want to replace - category/6 with category/anotherID.

The routing thats being used is:

routes.MapRoute(
      "categories",
      "category/{categoryID}/{categoryName}",
      new { controller = "Search", action = "SearchResults", categoryID = "", categoryName = "" }
);

thanks


You can use Regex.Replace() to replace the pattern '/category/\w+\?' by '/category/?'.

string newCategoryId = "333";
Regex regex = new Regex(@"/category/\w+\?");
string inputString = "http://localhost:1876/category/6?sortBy=asc&orderBy=Popular";
string replacementString = string.Format("/category/{0}?", newCategoryId);
string newUrl = regex.Replace(inputString, replacementString);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号