Walker News

Using Regular Expression To Insert nofollow Attribute To Hyperlink

While I was reading the Vim clever trick, the example of using regular expression to swap two words reminds me a similar challenge that I failed to solve.

So, here this post for me to remember the trick of using backreference, which should be useful to fix other cases related to regular expression in future.

Instead of copy and paste the example, I made own for reference – insert the nofollow attribute into hyperlink (the “a tag” in HTML).

Suppose this is the sample text:
Click <a href="example.com">here</a>.

Using Vi editor to run substitution command that use backreference of regular expression:
:s/<a\ \(.*\)">/<a\ \1" rel="nofollow">/

where the red text is “backreference” for blue text, i.e. the matched pattern (blue text) is stored to memory and then reuse it later for substitution (red text).
If that is too hard to understand, here is the breakdown for easier reading.

Search pattern:
<a\ \(.*\)">

<a\ \1" rel="nofollow">

Therefore, the result becomes this:
Click <a href="example.com" rel="nofollow">here</a>.

The screencast demos a similar example of using backreference of regular expression.
Note, the solution can be simple as this:
:s/<a /<a rel="nofollow" /

But, am just trying to show how to use backreference :)

Custom Search

2018  •  Privacy Policy