Find and Replace in Visual Studio Code

Ikechi Michael
2 min readFeb 4, 2018

--

It’s easy, and I’ll try to keep this short, I promise.

I have a markdown file with text like:

(1) The fox walked(2) Over the bridge  (a) To see its kids  (b) So they could see the hen    (i) It brought them for dinner    (ii) And they ate it all night

If you haven’t noticed already, the brackets notation is not accepted by markdown parsers as a way to represent lists.

So, we have to change it to something like:

1. The fox walked2. Over the bridge- (a) To see its kids- (b) So they could see the hen  - (i) It brought them for dinner  - (ii) And they ate it all night

For markdown to recognise and parse it as a list.

However, it’s a really long file and changing each line one by one is work, and I’m a lazy programmer.

So, we find and replace, right?

Luckily, VSCode is my editor and it lets me find and replace with regex as a tool, which gives us amazing flexibility.

Let’s do numbers first.

To find a single number in regex, we use \d, and two numbers could be \d\d.

We could use \d* to find zero or more numbers, or \d+ to find one or more consecutive numbers.

Now, to find a number that looks like (1),

  • we’d have to account for the fact that it’s at the beginning of a line, so we’d need to prefix it with \n.
  • we’d also have to select the brackets by escaping the ( character with \( and \).

Our regex becomes \n\((\d)\), which we can replace with \n$1. where $1 is used to represent the first group marked by brackets ( and ).

This replaces (1) with 1.

We can do the same for letters by replacing

\n \((\w)\) with \n- ($1)

and for Roman Numerals by replacing

\n +\((\w+)\) with\n — ($1)

How it works

$1 gives us a way to represent a regex group which is marked by being surrounded by brackets.

So, if you had a word like Hello World and you wanted to replace World with Africa in every instance of Hello World, then you find the text with

(Hello) World

which groups Hello as a single entity and makes it be represented by $1.

Our replace regex can then be $1 Africa.

You can have multiple groups and refer to each with $1, $2, etc respectively.

--

--

Ikechi Michael
Ikechi Michael

Written by Ikechi Michael

I’ve learned I don’t know anything. I've also learned that people will pay for what I know. Maybe that's why they never pay.

No responses yet