Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML anchor replace with RegEx

I have HTML data which I'll be using in a client app. I need to Regex.Replace the <a> tags from

<a href="Bahai.aspx">Bahai</a>

to

<a href="#" onclick="process('Bahai.aspx');return false;">Bahai</a>

In C# using RegExReplace with a regex similar to

<a[^>]*? href=\"(?<url>[^\"]+)\"[^>]*?>(?<text>.*?)</a>

Ideas?

like image 890
Ian Vink Avatar asked Feb 06 '26 06:02

Ian Vink


1 Answers

In C# you could use code like this:

Regex.Replace("<a href=\"Bahai.aspx\">Bahai</a>", 
            "<a href=\"(.+?)\">(.+?)</a>", "<a href=\"#\" onclick=\"process('$1');return false;>$2</a>",
            RegexOptions.IgnoreCase);

It will return a string that matches what you require.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!