产品有不同的型号,型号比如有a1,a2,b1,b2,b3,ab1,a 等等.
现在假设有a1,a2,a3,a4如何通过代码转换为a1~a4.
谢谢!
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);
如果是: 'a1,a2,a3,a5,a7,a8,a9' 能处理成: 'a1~a3,a5,a7~a9'么?
@袁家小黑球:
private void Form1_Load(object sender, EventArgs e)
{
var mystr = "产品有不同的型号,型号比如有ab1,ab2,b1,b2,b3,等等.现在假设有a1,a2,a3,a5,a7,a8,a9";
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)
{
var intStr = str.Replace(chart, "").Replace(" ", "");
var intLists = intStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (intLists.Length == count)
{
mystr = mystr.Replace(str, chart + intLists[0] + "~" + chart + count + ",");
continue;
}
var lists = new List<LianxuInt>();
var start = Convert.ToInt32(intLists[0]);
var mynum = Convert.ToInt32(intLists[0]);
for (var i = 0; i < intLists.Length; i++)
{
var num = Convert.ToInt32(intLists[i]);
if (num == mynum)
{
if (i == intLists.Length - 1)
{
var end = Convert.ToInt32(intLists[i]);
var lianxu = new LianxuInt
{
StartInt = start,
EndInt = end
};
lists.Add(lianxu);
break;
}
mynum = Convert.ToInt32(intLists[i])+1;
}
else
{
var end = Convert.ToInt32(intLists[i-1]);
var lianxu = new LianxuInt
{
StartInt = start,
EndInt = end
};
lists.Add(lianxu);
if (i==intLists.Length-1)
{
break;
}
start = mynum = Convert.ToInt32(intLists[i]);
i--;
}
}
var newStr = lists.Aggregate("", (current, list) => current + list.MyStr(chart));
mystr = mystr.Replace(str, newStr);
}
}
Console.WriteLine(mystr);
}
}
/// <summary>
/// 连续整数的起始与结束
/// </summary>
public class LianxuInt
{
public int StartInt { get; set; }
public int EndInt { get; set; }
public string MyStr(string chart)
{
return StartInt == EndInt ? chart + EndInt + "," : chart + StartInt + "~" + chart + EndInt + ",";
}
}
输出为:产品有不同的型号,型号比如有ab1~ab2,b1~b3,等等.现在假设有a1~a3,a5,a7~a9,
list<String>.Split()