i’m trying to find all the anchor tags and appending the href value with a variable.
for example
<a href="/page.aspx">link</a> will become <a href="/page.aspx?id=2">
<A hRef='http://www.google.com'><img src='pic.jpg'></a> will become <A hRef='http://www.google.com?id=2'><img src='pic.jpg'></a>
I’m able to match all the anchor tags and href values using regex, then i manually replace the values using string.replace, however i dont think its the efficient way to do this.
Is there a solution where i can use something like regex.replace(html,newurlvalue)
Yes you can. The standard warning applies — regular expressions are not sufficiently powerful to reliably parse html. In other words, it may actually work for you in the most straightforward & controlled examples, but there are many cases where this will fail.
However, if you already have the regular expression written then paste it into Regex Hero along with your HTML, click the “Replace” tab and type in your replacement string.
Once you’ve verified that it’s working click Tools > Generate .NET Code and you’ll have your answer.
UPDATE: So here’s an imperfect example of this in action using groups:
http://regexhero.net/tester/?id=e993fbf1-acb7-4f59-af87-94253a6e8221
The
(?<url>[^"]+)part is a named group that can be referenced in the replacement string as${url}.UPDATE #2:
So to only match the URL’s without a question mark you’d do this:
The
(?![^"]*\?)part is a negative lookahead that does the trick.