Regex to remove line numbers

I was looking at the Scala Swing test suite directly on the Scala EPFL repo web viewer and I wanted to try some parts of the tests myself quickly but I was feeling lazy to first fork the repo so I’ve copied the file and pasted on the IDE only to find that the line numbers were part of the copy action.

Then I realised that the repo web viewer actually provides a functionality to download the plain text but regardless that was a good excuse to fire up the IDE/text editor regex replace functionality!

The regex that did the trick:

find:      ^\s*\d{1,}(.*)$
replace:   \1

The ^ symbol represents the beginning of the line. The \s* part of the regex skips all spaces or tabs in the beginning of the line (if they exist at all). Then anticipates the line number comprised of 1 or more consecutive digits and from that point onwards captures the remaining of the line (the actual code) as a group. The $ part denotes the end of the line. The replace part presents the content of that first and only group.

A quirk I’ve found: IntelliJ IDE does not recognise in the replace section does not recognise the \1 as content of the group but would rather require to represent it as $1.

Advertisements

Vim how to replace leading line number from source file

Today I needed to replace the leading line number from a source file that was forwarded to me probably gotten from an html representation of a source repository of some sort. I know, definitely not the best way to acquire a source file this way but a good exercise nonetheless.

In Vim the following would do the trick:

:%s/^\s*\d\+//g

%    --> for each line
^    --> beginning of the current line
\s*  --> match any leading space characters
\d\+ --> match any number of digits (one or more)
     --> replace with nothing