public static string BlankSort(string content, out bool isSort) { List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>(); //content = "<span></span>现在国际上通用的质量单位是{#ZZZZ#}1{#/ZZZZ#}.国际上还流行“磅”这种质量单位,1磅=0.4536kg,<br>一名重量级拳击运动员质量为250磅,则250磅={#ZZZZ#}2{#/ZZZZ#}kg." //+ "<span></span>在国际单位制中,质量的基本单位是{#ZZZZ#}1{#/ZZZZ#};日常生活中常用的单位还有{#ZZZZ#}2{#/ZZZZ#}和{#ZZZZ#}3{#/ZZZZ#}."; MatchCollection coll = Regex.Matches(content, @"{#ZZZZ#}[s]*?(d{1,3})[s]*?{#/ZZZZ#}", RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.Singleline); isSort = true; if (coll.Count == 1) isSort = Convert.ToInt32(coll[0].Groups[1].Value) == 1 ? true : false; for (int i = 0; i < coll.Count - 1; i++) { var item_a = Convert.ToInt32(coll[i].Groups[1].Value);//1 var item_b = Convert.ToInt32(coll[i + 1].Groups[1].Value);//2 if (item_a + 1 != item_b) isSort = false; } if (isSort) return content; string str = content; var index = 0; for (int i = 0; i < coll.Count; i++) { index += str.IndexOf(coll[i].Groups[0].Value.ToString()); var item = coll[i].Groups[0].Value.ToString(); list.Add(new KeyValuePair<int, string>(index, item)); index = index + item.Length; str = content.Substring(index); } string con = content; for (var j = 0; j < list.Count; j++) { con = con.Substring(0, list[j].Key) + (content.Substring(list[j].Key, list[j].Value.Length).Replace(list[j].Value, "{#ZZZZ#}" + (j + 1) + "{#/ZZZZ#}")) + content.Substring(list[j].Key + list[j].Value.Length); } return con; }
问题:当存在这个一个字符串:{#ZZZZ#}1{#/ZZZZ#}斯蒂芬降温哦i{#ZZZZ#}1{#/ZZZZ#}隧道发生纠纷{#ZZZZ#}1{#/ZZZZ#}第三方{#ZZZZ#}1{#/ZZZZ#}时要求 把这个字符串改成:{#ZZZZ#}1{#/ZZZZ#}斯蒂芬降温哦i{#ZZZZ#}2{#/ZZZZ#}隧道发生纠纷{#ZZZZ#}3{#/ZZZZ#}第三方{#ZZZZ#}4{#/ZZZZ#}
思路:声明一个键值对集合 存:字符串中{#ZZZZ#}1{#/ZZZZ#}的当前的索引以及自身{#ZZZZ#}1{#/ZZZZ#}