Using Sublime Text 2 to do regex search and replace

Fun and useful for maxing out efficiency on search & replace

In Frontkom the texteditor Sublime Text 2 is almost universally used. Personally I love the look, the speed, the extensibility and the small tips I pick up nearly every day.

One nifty trick is the built-in regular expression search and replace which can be quite handy in a lot of situations.

For example I recently had an Excel document which had a lot of rows like this:

10x620x580mm

10x620x580mm

11x620x2390mm

11x620x2390mm

11x620x3050mm

and I want just the first number and “mm” added at the end, so I can paste it into a new column.

Now, there are probably some Excel wiz out there who would do this directly in Excel somehow, but since I always have Sublime open anyway I just copied the entire column into Sublime and hit the menu item Find->Replace and then activate regex search:

[scald=71:sdl_editor_representation]

Now we are ready to match the patterns on each row. As we can see, it starts with a number containing one or more digits. The regex code for a number is \d (for digit) and + is “one or more”. Now a nice thing in Sublime is that I can immediately see the pattern matching for all the rows simultaneously.

[scald=66:sdl_editor_representation]

Next it’s easy to match the rest of the line. Just match for the next “x”, digits and “mm”.

[scald=72:sdl_editor_representation]

Now, first we want the first number in the row, and add “mm” to it. To do that we should put a parenthesis around what we want. The first group can be outputted with $1, the second group with $2 and so on. Let’s Replace All with “$1mm”.

[scald=67:sdl_editor_representation]

And there we have the first number which can be pasted back into a new row in Excel or anywhere else.

[scald=68:sdl_editor_representation]

Or, let’s say we want to use all numbers and add som description, for example:

[scald=69:sdl_editor_representation]

Which will result in:

[scald=70:sdl_editor_representation]


Feel free to share your regex tricks in the comments!

Related articles

Get fresh perspective on digital change (temporary)   Get useful insights

0 replies on “Using Sublime Text 2 to do regex search and replace”

Leave your reply