2010-12-08 31 views
1

我需要一個正則表達式或任何其他解決方案來取代Url中間的一個id(不在查詢字符串中)。如何使用正則表達式替換Url中間的Id?

網址例如:

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

我想更換 - 類/ 6類/ anotherID

正在使用的路由多數民衆贊成是:

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

感謝

+0

這是ASP.NET嗎? ASP.NET MVC?你使用路由嗎?或者它只是一個隨機的URL?我發現你問的大部分問題都是關於ASP.NET MVC的,所以如果出現這種情況,請不要猶豫,重新提供有關你的路由的更多細節...... – 2010-12-08 09:16:48

回答

2

您可以使用Regex.Replace()來替代模式'/分類/ \ w + \?按'/ 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);