Link to home
Start Free TrialLog in
Avatar of tsabbay
tsabbay

asked on

RegEx.Replace c#

hi guys,
im trying to parse some html without success...
what i got is a string that holds an html.

i need to remove DIVS from it, but only if the div contains an image
with a specific src.

for example: this entire div should be replaced with an empty string...
<div><img src="bad.gif"></div>

and this should stay as is.
<div><img src="good.gif"></div>


what i was trying to do is using the following pattern :
<div.*bad.gif.*</div>

im new with regex so be gentle...(:
thx!
Avatar of ozo
ozo
Flag of United States of America image

<div((?!</div>).)*bad.gif.*?</div>
Hi, this method should strip out the div tags based on the src string you provide:

private string RemoveDivTagsBySrc(string html, string src)
{
      return Regex.Replace(html, "<div[^>]*>(.*?)<img(.*?)src=\"" + src + "\"[^>]*>(.*?)</div>", string.Empty, RegexOptions.IgnoreCase);
}

Usage:

string sampleHtml = "<div><img src=\"bad.gif\"></div>" + "\n" + "<div><img src=\"good.gif\"></div>" + "\n" + "<div><img src=\"bad.gif\"></div>";

string newHtml = this.RemoveDivTagsBySrc(sampleHtml, "bad.gif");

//newHtml string should now only contain the div tag with "good.gif" as the src
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tsabbay
tsabbay

ASKER

hi guys,
thank you all for your reply...while waiting i wrote a small string search and replace...
i checked both solutions and both not doing it right, sorry.

benny.
what are they not doing right?  If the div can include newlines, you should use RegexOptions.Singleline
bad.gif should really be bad\\.gif or bad[.]gif
ozo's right, my regex gets greedy and matches all the div tags, one way of using his regex is shown below:

(PLEASE ACCEPT THE SOLUTION BY OZO IF THIS WORKS FOR YOU)



private string RemoveDivTagsBySrc(string html, string src)
{
      return Regex.Replace(html, "<div((?!</div>).)*" + src + ".*?</div>", string.Empty, RegexOptions.IgnoreCase);
}

use:

string sampleHtml = "<div><img src=\"good.gif\"></div><div><img src=\"bad.gif\"></div>";
string newHtml = this.RemoveDivTagsBySrc(sampleHtml, "bad.gif");
Avatar of tsabbay

ASKER

i dnt know why...but its not just removing the relevant texts..its also removes some other divs closing tags from the html.

beside, my custom codes seems to work much faster then the regex so im dropping the usage.

thank you all for your time!
a credit will be givven to OZO.