/// <summary> /// 获取某字符串中间的字符串,非贪婪模式 /// </summary> /// <param name="input">全字符串</param> /// <param name="left">左边字符</param> /// <param name="right">右边字符</param> /// <returns></returns> public static List<string> GetCenterString(String input, String left, String right) { List<string> list = new List<string>(); Regex reg = new Regex(left + "(((?!" + left + ").)+?)" + right); foreach (Match m in reg.Matches(input)) { list.Add(m.Value); } return list; }
改进:添加参数是否包含左右字符
/// <summary> /// 获取某字符串中间的字符串,非贪婪模式 /// </summary> /// <param name="input">全字符串</param> /// <param name="left">左边字符</param> /// <param name="right">右边字符</param> /// <param name="isBorder">是否包含 left right 字符</param> /// <returns></returns> public static List<string> GetCenterString(String input, String left, String right, bool isBorder = true) { List<string> list = new List<string>(); Regex reg = new Regex(left + "(((?!" + left + ").)+?)" + right); foreach (Match m in reg.Matches(input)) { string value = m.Value; if (!isBorder) { value = value.Substring(left.Length, value.Length - left.Length); value = value.Substring(0, value.Length - right.Length); } list.Add(value); } return list; }
测试:
string all = @"这是一段测试数据{{dasdasdas}}这是一段测试数据{{ddd}{这是一段测试数据{{dasd}"; List<string> strList = StringPlus.GetCenterString(all, "{", "}");
输出结果:{dasdasdas}、{ddd}、{dasd}