Mar 21, 2011

Simple Regex example

So I had to do a quick search and replace on an xml file. The goal was to replace a pattern with another.

Example: Replace /2/215.html with &id2=2&id3=215

So here is a function to look for this pattern and replace with this other pattern:

static string ReplacePattern(Match m)
{
    var x = m.ToString();
    Console.WriteLine("Match is : " + x);

    var c = x.Count(f => f == '/'); // Or equivalent: x.Split('/').Length - 1;
    var slashIdx = x.IndexOf('/');

    for (int i = 0; i < c; i++)
    {
         var newPatt = string.Format("&id{0}=", (i + 2).ToString());
         x = slashIdx > 0 ? x.Substring(0, slashIdx) + newPatt + x.Substring(slashIdx + 1) : newPatt + x.Substring(slashIdx + 1);
         slashIdx = x.IndexOf('/', slashIdx + 1);
    }

    x = x.Replace(".html", string.Empty);

    Console.WriteLine("Replaced is: " + x);
    return x;
}

And here is a quick tester function:

private static void TestReplacePattern()
{
    string s = @"<loc>http://www.blabla.com/index.php?id=0/123/23/1/456/5.html";
    Regex r = new Regex("/[0-9/]+.html");
    Console.WriteLine(r.Replace(s, new MatchEvaluator(ReplacePattern)));
}

Mar 17, 2011

Refactor routine to use LINQ

Here is a function that does a bitwise XOR on a string

public string doIt(string input)
{
     var aChars = input.ToCharArray();
     var aCharsRes = new char[aChars.Length];

     for (int i = 0; i < aChars.Length; i++)
     {
          aCharsRes[i] = (char)(aChars[i] ^ 1);
     }
     return new string(aCharsRes);
}

Here is the re-factored one liner:

public string doItOneLiner(string input)
{
    return new string(input.ToCharArray().Select(s => (char)(s ^ 1)).ToArray());
}

Is it more readable? After getting used to LINQ, I guess.