DEV Community

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

Posted on

3

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay