DEV Community

Cover image for Replace anchor tags with square bracket format
Adam K Dean
Adam K Dean

Posted on

Replace anchor tags with square bracket format

For reason I won't go into, I have just found myself needing to replace a lot of anchor tags with square bracket format anchor tags, like so:

// from
<a href="#">link</a>

// to
[a href="#"]link[/a]
Enter fullscreen mode Exit fullscreen mode

Obviously, we need to use RegEx here, and for future reference mainly for myself, here are the matching and replacing patterns:

// match
<a .*?href=['""](.+?)['""].*?>(.+?)</a>

// replace
[a href="$1"]$2[/a]
Enter fullscreen mode Exit fullscreen mode

May as well put in the reverse as well:

// match
\[a .*?href=['""](.+?)['""].*?\](.+?)\[/a\]

// replace
<a href="$1">$2</a>
Enter fullscreen mode Exit fullscreen mode

And then if you're doing this in C#, just use this method:

string Regex.Replace(string input, string match, string replace)
Enter fullscreen mode Exit fullscreen mode

There we go, saved myself about a year of tedious work!

Top comments (0)