Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting "9954-4740-4491-4414" to "99:54:47:40:44:91:44:14" using Regular Expressions

Tags:

c#

regex

If the title isn't clear enough, here's a procedural way of approaching the problem:

[TestMethod]
public void Foo()
{
    var start = "9954-4740-4491-4414";

    var sb = new StringBuilder();
    var j = 0;
    for (var i = 0 ; i < start.Length; i++)
    {
        if ( start[i] != '-')
        {
            if (j == 2)
            {
                sb.AppendFormat(":{0}", start[i]);
                j = 1;
            }
            else
            {
                sb.Append(start[i]);
                j++;
            }
        }
    }

    var end = sb.ToString();

    Assert.AreEqual(end, "99:54:47:40:44:91:44:14");
}
like image 596
Merritt Avatar asked Dec 17 '22 02:12

Merritt


1 Answers

If you're using C# 4 all you need is this:

string result = string.Join(":", Regex.Matches(start, @"\d{2}").Cast<Match>());

For C# 3 you need to provide a string[] to Join:

string[] digitPairs = Regex.Matches(start, @"\d{2}")
                           .Cast<Match>()
                           .Select(m => m.Value)
                           .ToArray();
string result = string.Join(":", digitPairs);
like image 96
Mark Byers Avatar answered Jan 11 '23 22:01

Mark Byers