web 2.0

Clean up line numbered code samples with RegEx

Cake or Death RegEx Ever copied code off the web with those horrible leading line numbers?

Line numbered code sample:

   1: using System.Text;
   2:  
   3: namespace System.Web
   4: {
   5:     public sealed class HttpUtility
   6:     {
   7:         private static int HexToInt(char h)
   8:         {
   9:             if ((h >= '0') && (h <= '9'))
  10:             {
  11:                 return (h - '0');
  12:             }

It doesn't compile and your IDE doesn't know how to strip the line numbers. To fix the problem, pop open your favourite text editor with support for Regular Expressions (I use Notepad++) and sanitise that code!

RegEx search string:

*\d+\: (.*)

Replace string:

\1

This instructs the RegEx parser to replace each line with only the code part, which is matched by the first parentheses grouping: (.*).

Click Replace All and there you go - nice clean code:

using System.Text;
 
namespace System.Web
{
    public sealed class HttpUtility
    {
        private static int HexToInt(char h)
        {
            if ((h >= '0') && (h <= '9'))
            {
                return (h - '0');
            }

It is, beautiful.

Tags: , ,

Categories: Code

Comments are closed