A Ovest Di Paperino

Welcome to the dark side.

Regex & Lambda

Prima della cura:

private static string FormatLinks(string input, bool insideLink)

{

    MatchCollection matches = inlineUrls.Matches(input);

    if (matches.Count == 0)

    {

        return input;

    }

 

    StringBuilder sb = new StringBuilder(input.Length * 2);

 

    int inputIndex = 0;

    foreach (Match tag in matches)

    {

        // add the normal text between the
        // current index and the index of the current tag

        if (inputIndex < tag.Index)

        {

            sb.Append(input.Substring(inputIndex, tag.Index - inputIndex));

        }

 

        string url = tag.Value;

 

        sb.AppendFormat(insideLink ? "{1}" :
         "<a target='blank' href='{0}'>{1}</a>", url,
         HtmlHelper.ReduceUrlLength(url, maxUrlLength));

        inputIndex = tag.Index + tag.Length;

    }

 

    // add remainder

    if (inputIndex < input.Length)

    {

        sb.Append(input.Substring(inputIndex));

    }

 

    return sb.ToString();

}

Dopo la cura

private static string FormatLinks(string input, bool insideLink)

{

    return inlineUrls.Replace(input, m =>

        {

 

            return String.Format(insideLink ?
           "{1}" : "<a target='blank' href='{0}'>{1}</a>",
             m.Value,
            HtmlHelper.ReduceUrlLength(m.Value, maxUrlLength));

        }

    );

}

Interessante anche il fatto che, sebbene normalmente le lambda siano meno leggibili, nel caso specifico la riduzione di codice ridondante rende l’intenzione più evidente.

-quack

P.S. è un periodo in cui sniffo RegEx da mattina a sera; dienticavo: grazie all’enorme lavoro di refactoring i link nella nuvoletta sono ora cliccabili, per la gioia di Dovella