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
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
- 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
- we’d also have to select the brackets by escaping the
Our regex becomes
\n\((\d)\), which we can replace with
$1 is used to represent the first group marked by brackets
We can do the same for letters by replacing
\n \((\w)\) with
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
Africa in every instance of
Hello World, then you find the text with
Hello as a single entity and makes it be represented by
Our replace regex can then be
You can have multiple groups and refer to each with
$2, etc respectively.