求一个C#字符串截取方法:

来源:百度知道 编辑:UC知道 时间:2024/04/29 21:24:15
string url="www.abc.com/news/shanghai.aspx?id=105"
string file="" //网页文件名

file = url.Substring(url.LastIndexOf("/") + 1);
这个方法的话,结果file="shanghai.aspx?id=105"

我的要求是从最后一个“/”开始截取,取到第一个“.aspx”之前。
上面的url截取后的值应为file="shanghai"

劳请大师们指教一下,3Q

string url = "www.abc.com/news/shanghai.aspx?id=105";
string file = url.Substring(url.LastIndexOf("/") + 1, url.IndexOf(".aspx") - url.LastIndexOf("/") - 1);

应用正则表达式,代码如下(已经测试通过):
string strText = "www.abc.com/news/shanghai.aspx?id=105";
string RegText = @".*/(.*?).aspx\?id=\d+";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(RegText, System.Text.RegularExpressions.RegexOptions.Singleline);
System.Text.RegularExpressions.MatchCollection _Matches = reg.Matches(strText);
string UrlFileName = _Matches[0].Groups[1].Value;

再把file来个substring不就行了
file="shanghai.aspx?id=1