Greetings!
I have some HTML that may or may not be valid. If the HTML is invalid, a best attempt can be made, and any errors that arise are acceptable (ie, grouping too much because some tag isn’t closed correctly).
In this HTML are a variety of elements, some of which may have a class (call it “findme”). These elements are of varying type; some img, some object, some a, etc.
I need a regex that will pull out all the elements, and the content they contain if they contain content.
For example:
<div>
<span><img class="findme" src="something" /></span>
<object class="findme" classid="clsid:F08DF954-8592-11D1-B16A-00C0F0283628" id="Slider1" width="100" height="50">
<param name="BorderStyle" value="1" />
<param name="MousePointer" value="0" />
<param name="Enabled" value="1" />
<param name="Min" value="0" />
<param name="Max" value="10" />
</object>
</div>
Running the regex on that chunk of HTML should return 2 elements:
<img class="findme" src="something" />
and
<object class="findme" classid="clsid:F08DF954-8592-11D1-B16A-00C0F0283628" id="Slider1" width="100" height="50">
<param name="BorderStyle" value="1" />
<param name="MousePointer" value="0" />
<param name="Enabled" value="1" />
<param name="Min" value="0" />
<param name="Max" value="10" />
</object>
Any of you regex gurus out there have an idea on this one?
Edit:
The language is c#.
While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.
What I recommend you do is use a DOM parser such as
SimpleHTMLand use it as such:Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.
A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the
altattribute to be after thesrcor the opposite, and to overcome this limitation would add more complexity to the regular expression.Also, consider the following. To properly match an
<img>tag using regular expressions and to get only theclassattribute (captured in group 2), you need the following regular expression:And then again, the above can fail if:
imodifier is not used.classattribute.classuses the>character somewhere in their value.So again, simply don’t use regular expressions to parse a dom document.