We help IT Professionals succeed at work.

parse portion of HTML - count of certain tag - C# RegEx code needed

Tom Knowlton
Tom Knowlton asked
on
This section of the HTML is of interest to me:

<select name="ctl00$ContentPlaceHolder1$dlStore" id="ctl00_ContentPlaceHolder1_dlStore" disabled="disabled" title="Store" style="text-align: left">
            <option value="NULL">Select Campus...</option>
            <option selected="selected" value="1">KSU ASHTABULA</option>
</select>

This will be surrounded by other HTML, but it is just this block of code that I want to extract and examine.

Within this block of code, above, I want to check for HOW MANY <option></option> pairings there are.  If there is only one I want to do one thing.  If there are more than one I want to do another thing.

So the logic would be:

(A) Isolate the portion of code above.  Perhaps use the existence of "dlStore" in the id to identifiy the <select></select> block
(B) in this block of code we isolate in (A), count how many times there is an <option></option> pairing.
(C) do something based on the count.


Please provide tested working C# source code if you can.

I am using C# in a windows app to do this....I will favor a working C# .NET response over something more generic.
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Try this:

int count = System.Text.RegularExpressions.Regex.Matches(input, @"(?s)(?<=<select name=""ctl00\$ContentPlaceHolder1\$dlStore"".*?)<option[^<]+</option>").Count;

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
I need to make a correction. Stand by.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Corrected:

int count = System.Text.RegularExpressions.Regex.Matches(input, @"(?s)(?<=<select name=""ctl00\$ContentPlaceHolder1\$dlStore""([^<]|<(?!select ))*?)<option[^<]+</option>").Count;

Open in new window


The previous suggestion would also have found <option> tags located in <selects> that came after your target <select>. This new version should not.
Tom KnowltonWeb developer

Author

Commented:
Plugged in your code...seems to be ship shape and in Bristol fashion!

Thank you!

http://www.phrases.org.uk/meanings/ship-shape%20and%20Bristol%20fashion.html
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Heheh. Thanks! Glad to help  = )

Explore More ContentExplore courses, solutions, and other research materials related to this topic.