我有以下代码,我从字符串列表创建一个正则表达式,这完全满足我的需要。我想知道是否有一个单行方式这样做?
using System;
class Program
{
static void Main(string[] args)
{
string[] idlist1 = new string[] { };
string[] idlist2 = new string[] { };
string[] idlist3 = new string[] { };
string id1 = "ABC1234.PIL.5.0-00028-P-1";
string id2 = "DEF5678.PIL.5.0-00028-E-1";
string id3 = "GHI9101.PIL.4.0-00135-B-1";
idlist1 = id1.Split('-');
idlist2 = id2.Split('-');
idlist3 = id3.Split('-');
//create a regex of type ABC1234.PIL.5.0*P*
//create a regex of type DEF5678.PIL.5.0*E*
//create a regex of type GHI9101.PIL.4.0.B*
string regex1 = idlist1[0] + "*" + idlist1[2] + "*" ;
string regex2 = idlist2[0] + "*" + idlist2[2] + "*";
string regex3 = idlist3[0] + "*" + idlist3[2] + "*";
Console.WriteLine(regex1);
Console.WriteLine(regex2);
Console.WriteLine(regex3);
Console.ReadLine();
}
}
答案 0 :(得分:2)
一个班轮?当你可以将这个操作移动到一个方法时,这似乎是一个不必要的优化...
public string GetRegex(string idString)
{
string[] idlist = new string[] { };
idlist = idString.Split('-');
string regex = idlist[0] + "*" + idlist[2] + "*";
return regex;
}
答案 1 :(得分:0)
转到@Callback Kid的回答:
public string GetRegex(string idString)
{
string[] idlist = { };
idlist = idString.Replace('-', '*').Split('*');
return string.Concat(idlist[0], idlist[2]);
}
答案 2 :(得分:0)
这是您问题中所有代码的单线解决方案:)
new string[] {"ABC1234.PIL.5.0-00028-P-1", "DEF5678.PIL.5.0-00028-E-1", "GHI9101.PIL.4.0-00135-B-1"}.Select(x => Regex.Replace(x, "-.+-(.)-.", "*$1*")).ToList().ForEach(x => Console.WriteLine(x));
虽然,为了更好地理解它。 。
new string[]
{
"ABC1234.PIL.5.0-00028-P-1", "DEF5678.PIL.5.0-00028-E-1", "GHI9101.PIL.4.0-00135-B-1"
}
.Select(x => Regex.Replace(x, "-.+-(.)-.", "*$1*"))
.ToList()
.ForEach(x => Console.WriteLine(x));
对于单个条目的实际创建,您可以使用这一个内容
Console.WriteLine(Regex.Replace("ABC1234.PIL.5.0-00028-P-1", "-.+-(.)-.", "*$1*"))