Dwi Wahyudi
Senior Software Engineer (Ruby, Golang, Java)
Some moment ago I’m in the condition where I need to capture some fragments of texts with regex and replacing such texts and fill it with the captured fragments.
Overview
During the course of updating this blog, I found a library that can make my images more visible by clicking it. It takes all image
tags enclosed with specific class of a
tag, it will then tranform those images into clickable ones. Clicking the image will display it upfront with larger size.
Check this library: lightbox2
However I found out that I need to update all of my image tags to be enclosed with a
tag. A simple find and replace in any text editor won’t work.
I also needed to preserve the width values for each images.
I could just inspect all of my blog posts and updating it one by one, but doing so would take considerable amount of time. So I decided to use regex find and replace feature available in VS Code to do it.
I need to transform this one:
<img class="img-fluid" src="/images/golang-jaeger/web-ui.png" width="100%"/>
…to this one:
<a href="/images/golang-jaeger/web-ui.png" data-lightbox="image-0">
<img class="img-fluid" src="/images/golang-jaeger/web-ui.png" width="100%"/>
</a>
Let’s Capture Them
I need to capture 2 things: the src
and the width
. I can just simply capture the values by using ()
, each of the captured fragments would then be stored as $1
, $2
, $3
, and so on for us to use in replace field.
So let’s replace this sample texts:
<img class="img-fluid" src="/images/golang-jaeger/web-ui.png" width="100%"/>
<img class="img-fluid" src="sample-image.png" width="90%"/>
<img class="img-fluid" src="sample-image-2.png" width="70%"/>
<img class="img-fluid" src="sample-image-3.png" width="70%"/>
Find and capture with this:
<img class="img-fluid" src="(.*)" width="(.*)"/>
… and replace them one by one with this:
<a href="$1" data-lightbox="image-0">
<img class="img-fluid" src="$1" width="$2"/>
</a>
This means find every regex match of those, capture what’s inside ()
, for every capture, store it into $1
, $2
, and so on variables, this case it would be the src
values and width
values, then replace it with new text, insert the captured values. And after replacing them with regex, the result would be like this:
<a href="/images/golang-jaeger/web-ui.png" data-lightbox="image-0">
<img class="img-fluid" src="/images/golang-jaeger/web-ui.png" width="100%"/>
</a>
<a href="sample-image.png" data-lightbox="image-0">
<img class="img-fluid" src="sample-image.png" width="90%"/>
</a>
<a href="sample-image-2.png" data-lightbox="image-0">
<img class="img-fluid" src="sample-image-2.png" width="70%"/>
</a>
<a href="sample-image-3.png" data-lightbox="image-0">
<img class="img-fluid" src="sample-image-3.png" width="70%"/>
</a>
This is how it will look like in VS Code find and replace feature:
We can also apply such thing for all of the codes in the project/workspace.