【问题标题】:Extract Portion of the URL after "Home"提取“主页”之后的 URL 部分
【发布时间】:2019-01-03 13:11:38
【问题描述】:

我需要在“home”之后提取 URL 的其余部分

例如,网址可以是

https://www.example.com/site/country/home/products
https://www.example.com/site/country/home/products/consumer
https://www.example.com/site/country/home/products/consumer/kids

url“site”、“country”中的关键字可能会改变。

我只需要输出:

 /products 
 /products/consumer 
 /products/consumer/kids

我尝试使用正则表达式,但在上述情况下不起作用

【问题讨论】:

  • 找到“/home/”的第一个索引并取其后的子字符串?
  • 你试过什么正则表达式?另外,为什么不直接使用String.IndexOf()
  • Something like this should workstring rest = url.Substring(url.IndexOf("/products"));

标签: c# regex string substring


【解决方案1】:

正如 Corion 和 David 在 cmets 中所建议的那样,在这种情况下,最简单的方法可能只是找到 /home/ 的索引,然后剥离直到该点的所有内容(但不是第二个 /):

string home = "/home/";
int homeIndex = url.IndexOf(home);
string relativeUrl = url.Substring(homeIndex + home.Length - 1);

使用正则表达式,您想匹配 /home/ 子字符串,并捕获第二个 / 及其后面的所有内容:

Match match = Regex.Match(url, @"/home(/.*)");
string relativeUrl = "/";
if (match.Success) {
    relativeUrl = match.Groups[1].Value;
}

【讨论】:

  • @SitecoreSXADeveloper 我刚刚修好了。
【解决方案2】:

这是一个非常简单的 c# 代码,我认为它可以帮助你

string sub = "https://www.example.com/site/country/home/products";
        string temp = "";
        string[] ss = sub.Split('/');
        for(int i = 0; i < sub.Length; i++)
        {
            if (ss[i] == "home")
            {
                i++;
                for (int j = i; j < ss.Length; j++)
                    temp +='/'+ ss[j];

                break;
            }

        }
        Console.WriteLine(temp);

【讨论】:

  • 虽然比这里的大多数答案都通用,但是没必要拆分循环;只需找到home 的索引并获取子字符串。
  • 我只给出一个想法,我认为 indexof 只获取字符,indexofany 获取字符数组,但可能没有排序
  • 这确实不是一个坏主意,但代码的工作量比需要的要多得多,这种方法最好使用 Crowcoder 对System.Uri 的回答。此外,您应该在for 循环中检查ss.Length 而不是sub.Lengthstring.IndexOf 会在字符串中找到一个子字符串的起始索引,所以在这种情况下它可以工作。
【解决方案3】:

您可以使用System.Uri 类来提取 URL 的片段:

Uri link = new Uri("https://www.example.com/site/country/home/products/consumer/kids");
string[] segs = link.Segments;

int idxOfHome = Array.IndexOf(segs, "home/");

string restOfUrl = string.Join("", segs, idxOfHome+1, segs.Length  - (idxOfHome + 1));

产量:

产品/消费者/儿童

【讨论】:

  • 段的问题是,如果我在 url 中有一个空格,它会返回编码形式。在我的 /products/consumer/for men 的情况下,它返回 /products/consumer/for%40men 然后我只使用了 Trim 和 IndexOf。
  • 你可以对它进行 URL 解码,但这不是它的空间@
【解决方案4】:

使用正则表达式很容易。请使用以下正则表达式并测试您的场景。它工作正常。

正则表达式:'(?&lt;=\/home).*\b'

回家前无需担心前部。一旦找到家,它就会在回家后说话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多