2010-12-08 81 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);