今天在论坛上看到帖子回复,对于正则的应用不熟练,遂记录下来,以便日后查找。 /// <summary> /// 截取网站地址 /// </summary> /// <param name="url">网址,http://localhost:50759/ETCB2B/a/b/c/Default.aspx</param> /// <returns>http://localhost:50759/ETCB2B</returns> public string JieQuAddress(string url) { url = "http://localhost:50759/ETCB2B/a/b/c/Default.aspx"; int i = 0; string result = Regex.Replace(url, @"(?<=/)[^/]*", delegate(Match m) {i++; if (i < 4){return m.Value;} else {return "";}}); return result.TrimEnd('/'); } 注意:需要添加引用using System.Text.RegularExpressions;