2
args.Content;

Is dynamic.

On this example it has this value and it represents a script input:

<div class="b-db">
<span class="b-db-ac b-db-ac-th" role="button"></span>
<span class="b-db-ac b-db-ac-th" role="button"></span>
<span class="b-db-ac b-db-ac-th" role="button"></span>
<span class="b-db-ac b-db-ac-th" role="button"></span>
<span class="b-db-ac" role="button"></span>
</div>

How do you count number of instances of span with the class="b-db-ac b-db-ac-th"?

On this example output should be: 4

sebas
  • 722
  • 1
  • 6
  • 21

2 Answers2

4

When you are working with html, use a real html parser like HtmlAgilityPack

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(DATA);

var count = doc.DocumentNode.SelectNodes("//span[@class='b-db-ac b-db-ac-th']")
               .Count();

You can even use pure Linq

var count2 = doc.DocumentNode.Descendants("span")
                .Where(s => s.Attributes["class"]!=null && 
                            s.Attributes["class"].Value == "b-db-ac b-db-ac-th")
                .Count();
EZI
  • 15,209
  • 2
  • 27
  • 33
  • Can't use any external parser for this application, any suggestion ? – sebas Oct 07 '14 at 17:25
  • @sebas then your best bet would be Regex, but I wouldn't recommend it. See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – EZI Oct 07 '14 at 17:27
  • @sebas Maybe you want to try `Regex.Matches(DATA, @"().Count();` – EZI Oct 07 '14 at 17:33
  • Thanks, but it's giving me an empty output – sebas Oct 07 '14 at 17:53
  • @sebas No it returns 4, Your test data may be different than the one you posted here. (BTW: `Count()` can not give an empty output, either a number or an exception) – EZI Oct 07 '14 at 21:11
  • Sorry i dont know regex, this returns the html input from my OP (.*) How can I use your regex code to output "4"? – sebas Oct 07 '14 at 22:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/62636/discussion-between-sebas-and-ezi). – sebas Oct 07 '14 at 22:35
1

You'll want to use HtmlAgilityPack. You'll want to query specifically on the b-db-ac-th CSS class to get the 4 elements you requested in your question.

This code isn't meant to be copy/pasted but should give you the direction you need to accomplish what you're looking to do.

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(args.Content);
var count = doc.DocumentNode.SelectNodes("//span").Count( d=> d.Attributes["class"].Value == "b-db-ac b-db-ac-th" );
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49