C#字符串处理,通过波浪号合并

产品有不同的型号,型号比如有a1,a2,b1,b2,b3,ab1,a 等等.

现在假设有a1,a2,a3,a4如何通过代码转换为a1~a4.

谢谢!


慕姐8265434
浏览 742回答 1
1回答

紫衣仙女

var mystr = "产品有不同的型号,型号比如有ab1,ab2,b1,b2,b3,等等.现在假设有a1,a2,a3,a4";var matches = Regex.Matches(mystr, @"([a-z]+)\d+\s*[,,]\s*(\1(\d+)(?:\s*[,,]\s*)*)*");foreach (Match match in matches){  if (string.IsNullOrEmpty(match.Groups[3].Value))  {    continue;  }  var str = match.Value;  var chart = match.Groups[1].Value;  var count = Convert.ToInt32(match.Groups[3].Value);  if (count>1)  {    mystr = mystr.Replace(str, chart + "1~" + chart + count+",");  }}Console.WriteLine(mystr);
打开App,查看更多内容
随时随地看视频慕课网APP