C# 提取URL中“引用”之后的部分;“家”;

C# 提取URL中“引用”之后的部分;“家”;,c#,regex,string,substring,C#,Regex,String,Substring,我需要提取URL中“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“站点”、“国家”中的关键字可能会更改 我在输出中只需要: /produ

我需要提取URL中“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“站点”、“国家”中的关键字可能会更改

我在输出中只需要:

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

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

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


正则表达式:
”(?正如Corion和David在评论中所建议的,在这种情况下,最简单的方法可能只是找到
/home/
的索引,然后将所有内容剥离到该点(但不是第二个
/
):

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

Match match = Regex.Match(url, @"/home(/.*)");
string relativeUrl = "/";
if (match.Success) {
    relativeUrl = match.Groups[1].Value;
}
这是一个非常简单的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);
stringsub=”https://www.example.com/site/country/home/products";
字符串temp=“”;
字符串[]ss=sub.Split('/');
对于(int i=0;i
您可以使用
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));
Yeilds:

产品/消费者/儿童


找到“/home/”的第一个索引,然后获取子字符串?您尝试了什么正则表达式?另外,为什么不使用?
string rest=url.substring(url.IndexOf(“/products”))
虽然它比这里的大多数答案更一般,但不需要拆分和循环;只需找到
home
的索引并获取子字符串。我只给出了一个想法,我认为indexof get only character和indexofany get array of character,但可能没有顺序。这不是一个好主意,但代码的工作量比实际情况要大得多需要,这种方法最好使用Crowcoder对
System.Uri
的回答。此外,您应该检查
ss.Length
,而不是
for
循环中的
sub.Length
string.IndexOf
将在字符串中找到子字符串的起始索引,因此它在这种情况下有效。@SitecoreSXADeveloper I just修复了它。segments的问题是,如果url中有一个空格,它将返回编码的表单。在我的例子中,对于/products/consumer/对于男性,它返回/products/consumer/对于%40men,那么我只使用了Trim和IndexOf。你可以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));