首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何删除Url中带括号的部分

如何删除Url中带括号的部分
EN

Stack Overflow用户
提问于 2016-11-09 02:37:33
回答 1查看 121关注 0票数 1

在我的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

我还希望它能够智能地删除路径中间的项,这样如果url是:api.domain.com/users/{id}/photos

我会得到:api.domain.com/users/photos

为此,我不会提前知道密钥的文本,因此{id}可以是以下任何内容:

{name} {sometext} {anyvalue}

但我知道每一个都必须包含在大括号中。

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2016-11-09 03:03:06

你可以这样做:

代码语言:javascript
运行
复制
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
}

然后你就会像这样使用它

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40494144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档