Reputation: 11476
I have the following code where I create a regex from a list of strings,this perfectly suffices my need.I was wondering if there a one liner way of doing this?
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();
}
}
Upvotes: 0
Views: 244
Reputation: 169
Here's a one liner solution to all your code in your question :)
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));
Though, to better understand it . . .
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));
for just the actual creation of a single entry, you can use this one liner
Console.WriteLine(Regex.Replace("ABC1234.PIL.5.0-00028-P-1", "-.+-(.)-.", "*$1*"))
Upvotes: 0
Reputation: 383
Tweak to @Callback Kid's answer:
public string GetRegex(string idString)
{
string[] idlist = { };
idlist = idString.Replace('-', '*').Split('*');
return string.Concat(idlist[0], idlist[2]);
}
Upvotes: 0
Reputation: 718
A one liner? seems like an unnecessary optimization, when you could move this operation to a method...
public string GetRegex(string idString)
{
string[] idlist = new string[] { };
idlist = idString.Split('-');
string regex = idlist[0] + "*" + idlist[2] + "*";
return regex;
}
Upvotes: 2