【问题标题】:How to remove bracketed sections of a Url如何删除 URL 的括号部分
【发布时间】:2017-03-22 12:09:02
【问题描述】:

在我的 c# 应用程序中,我正在构建一个例程,它将通过 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}

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

任何帮助将不胜感激!

【问题讨论】:

  • 可以调整为使用 {0} 并替换为 string.Format() 吗?
  • 到目前为止,您尝试完成什么?你能发布这个“我正在构建一个将通过 url 解析替换任何部分的例程”
  • 2 分:1. if(path.Contains("{id}") path = path.Replace("{id}", id) - 你不需要包含检查。你可以只做.Replace(),它只会在它实际存在时替换它。 2.为什么你不能总是在中间使用替换?即使有双斜杠,该 URL 仍然有效。
  • @TotZam 对于 2,我实际上并不提前知道要替换括号之间的文本。
  • 您是否故意不使用 RouteConfig,因为您似乎基本上是手动执行此操作?例如:tutorialsteacher.com/mvc/routing-in-mvc

标签: c# regex url


【解决方案1】:

你可以这样做:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多