Lucas Vieites .com Logo
Lucas Vieites .com
«I intend all my puns»

Search and replace with regular expressions in the Atom editor

 

When you need to search and replace, but you want to replace the found string with a text including that string, it gets complicated. The Atom text editor (now deprecated) uses the Javascript RegExp engine and you can capture the found string and reuse it when replacing.

For this example I'm going to find all strings that start with the letters "KB" and then a group of 7 digits, eg, KB0989483, and then replace that string with a MarkDown link containing that same reference number.

Searching for the string is as simple as using the following regular expression (see "Find and Replace" to find out how to enable regex search in atom):

KB[0-9]{7}

This regular expression says: find the letters "KB", followed by any number between 0 and 9, exactly 7 times.

We want to reuse the text we find in our "replace" string. For that, we will need to capture it in a variable. That's done by placing parenthesis around the expression, and using "$1" in the "replace" field as many times as we want:

(KB[0-9]{7}) [$1](https://my.knowledgebase.example.com/kb_view.php?kbnr=$1)

You can also use capture multiple strings and use $1, $2, etc. as the replacer. Just use the parentheses several times, for example, if you have a text file with lines in this format...

left 001
right 002
right 003

...and you want to reverse the order of the words, you can use this "find" regex...

^(\w+)\s(\d+)$

...and replace with...

$2 $1

...which will leave you with...

001 left
002 right
003 right

Author:   ✦  Published:   ✦  Updated:   ✦