C# 如何删除Url中带括号的部分
在我的c#应用程序中,我正在构建一个例程,该例程将通过url进行解析,并用适当的数据替换url的任何部分 例如,如果我有一个url,如:C# 如何删除Url中带括号的部分,c#,regex,url,C#,Regex,Url,在我的c#应用程序中,我正在构建一个例程,该例程将通过url进行解析,并用适当的数据替换url的任何部分 例如,如果我有一个url,如: api.domain.com/users/{id} 当用户提供id时,我用给定的值替换id 这很简单: if(path.Contains(“{id}”)path=path.Replace(“{id}”,id); 但是,如果没有提供id,我希望能够从url中删除{id},以便最终url为: api.domain.com/users 我也希望它能够智能地删除路径中
api.domain.com/users/{id}
当用户提供id时,我用给定的值替换id
这很简单:
if(path.Contains(“{id}”)path=path.Replace(“{id}”,id);
但是,如果没有提供id,我希望能够从url中删除{id}
,以便最终url为:
api.domain.com/users
<>我也希望它能够智能地删除路径中间的项目,如果URL是:
api.domain.com/users/{id}/photos
我会得到:
api.domain.com/users/photos
因此,我不会提前知道密钥的文本,因此{id}
可以是以下内容:
{name}{sometext}{anyvalue}
但我知道每一个都必须用大括号括起来
非常感谢您的帮助!您可以这样做:
public string UrlReplace(string Url, string key, string value = "")
{
var replaceString = "{" + key + "}"; //get the string to replace
//if the value is empty remove the slash
if (string.IsNullOrEmpty(value))
{
//find the index of the replace string in the url
var index = url.IndexOf(replaceString) + replaceString.Length;
if (url[index] == '/')
{
url = url.Remove(index, 1); //if the character after the string is a slash, remove it
}
}
return url.Replace(replaceString, value); //replace the string with the value
}
那么你会像这样使用它
string url = "api.domain.com/users/{id}/photos";
url = UrlReplace(url,"id","test");
//returns "api.domain.com/users/test/photos"
url = UrlReplace(url, "id", "");
//returns "api.domain.com/users/photos"
您可以这样做:
public string UrlReplace(string Url, string key, string value = "")
{
var replaceString = "{" + key + "}"; //get the string to replace
//if the value is empty remove the slash
if (string.IsNullOrEmpty(value))
{
//find the index of the replace string in the url
var index = url.IndexOf(replaceString) + replaceString.Length;
if (url[index] == '/')
{
url = url.Remove(index, 1); //if the character after the string is a slash, remove it
}
}
return url.Replace(replaceString, value); //replace the string with the value
}
那么你会像这样使用它
string url = "api.domain.com/users/{id}/photos";
url = UrlReplace(url,"id","test");
//returns "api.domain.com/users/test/photos"
url = UrlReplace(url, "id", "");
//returns "api.domain.com/users/photos"
可以调整为使用{0}并替换为string.Format()?到目前为止您尝试了什么来完成此操作?您是否可以发布以下内容“我正在构建一个例程,它将通过url解析替换任何部分”2点:1。
if(path.Contains(“{id}”)path=path.replace(“{id}”,id)
-不需要包含检查。只需执行.Replace()
只有在它实际存在时才会替换它。2.为什么不能始终在中间使用替换?即使有双斜杠,URL仍然有效。@TotZam对于2,我实际上事先不知道括号之间有什么文本要替换。你是故意不使用RouteConfig,因为看起来你是b吗基本上是手动完成的?例如:可以调整为使用{0}并替换为string.Format()?到目前为止您尝试了什么来完成此操作?您是否可以发布此“我正在构建一个例程,将通过url解析替换任何部分”2点:1。if(path.Contains({id})path=path.replace({id}),id)
-不需要包含检查。只需执行.Replace()
只有在它实际存在时才会替换它。2.为什么不能始终在中间使用替换?即使有双斜杠,URL仍然有效。@TotZam对于2,我实际上事先不知道括号之间有什么文本要替换。你是故意不使用RouteConfig,因为看起来你是b吗手动操作的基本原理?例如: