使用c#查找字符串?

使用c#查找字符串?,c#,asp.net,vb.net,C#,Asp.net,Vb.net,我试图在下面的字符串中找到一个字符串 http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779 通过使用http://example.com/TIGS/SIM/Listsstring。如何从中获得团队讨论信息 有时字符串会被删除 http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779 I need `Tea

我试图在下面的字符串中找到一个字符串

http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779
通过使用
http://example.com/TIGS/SIM/Lists
string。如何从中获得
团队讨论
信息

有时字符串会被删除

   http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779
     I need `Team Discussion`

http://example.com/TIGS/ALIF/Lists/Artifical Lift Discussion Forum 2/DispForm.aspx?ID=8

    I need  `Artifical Lift Discussion Forum 2`

这里有一个简单的方法,假设您的URL在“您想要什么”之前总是有相同数量的斜杠:

var value = url.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries)[5];

如果你总是遵循这个模式,我推荐@Justin的答案。但是,如果您想要一个更健壮的方法,则始终可以将
System.Uri
Path.GetDirectoryName
方法耦合,然后执行
String.Split
。比如:


但是,唯一的主要问题是,如果您想查看正则表达式示例,您将得到一个已“编码”的路径(即,您的空间现在将由一个
%20
表示):

        string input = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx?ID=1779";
        string given = "http://example.com/TIGS/SIM/Lists";
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(given + @"\/(.+)\/");
        System.Text.RegularExpressions.Match match = regex.Match(input);
        Console.WriteLine(match.Groups[1]); // Team Discussion

无论URL中有多少个目录,此解决方案都将为您获取URL的最后一个目录

string[] arr = s.Split('/');
string lastPart = arr[arr.Length - 2];

您可以将此解决方案合并为一行,但是需要将字符串拆分两次,一次用于值,第二次用于长度。

这里是另一种解决方案,它提供了以下优点:

  • 不需要使用正则表达式
  • 不要求存在特定的斜杠“计数”(基于特定数字的索引)。我认为这是一个关键的好处,因为如果URL的某些部分发生更改,代码就不太可能失败。最后,最好把语法逻辑从你认为最不可能改变的文本结构的哪一部分开始。
<>这个方法确实依赖于以下假设,我认为这是最不可能改变的:

  • URL必须在目标文本前面有“/Lists/”
  • URL必须在目标文本后面有“/”
基本上,我只是将字符串拆分两次,使用我希望围绕我感兴趣的区域的文本

String urlToSearch = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx";
String result = "";

// First, get everthing after "/Lists/"
string[] temp1 = urlToSearch.Split(new String[] { "/Lists/" }, StringSplitOptions.RemoveEmptyEntries);                
if (temp1.Length > 1)
{
    // Next, get everything before the first "/"
    string[] temp2 = temp1[1].Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
    result = temp2[0];
}

然后,您的答案将存储在“result”变量中。

有点不同的方法;将其加载到
Uri
中,并使用
Parts
属性。
String urlToSearch = "http://example.com/TIGS/SIM/Lists/Team Discussion/DispForm.aspx";
String result = "";

// First, get everthing after "/Lists/"
string[] temp1 = urlToSearch.Split(new String[] { "/Lists/" }, StringSplitOptions.RemoveEmptyEntries);                
if (temp1.Length > 1)
{
    // Next, get everything before the first "/"
    string[] temp2 = temp1[1].Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
    result = temp2[0];
}