Link to home
Create AccountLog in
Avatar of aaron900
aaron900

asked on

Regex - match a select list's selected option's text and value


Trying to extract the selected option from a select list such as:

<select name="chk_prequalify"><option value="">(select)</option><option value="N">No</option><option value="Y" selected>Yes</option></select>

The regular expression of:
<select [^>]*(?<=name="chk_prequalify"[^<]*)>.*?<option[^>]*selected.*?>(.*?)</option>.*?</select>
works great, so long as that select list has "selected" in one of the options. If I don't have a "selected" in the text to search, it goes down to the next occurrence of where it finds selected (possibly WAY down) and grabs that.

So my question is, using the select list shown above:
How can I extract the "Yes" for selected? And,
How can I extract the "Y" for the value of that selected option?

These would of course be two different regular expressions. But I do need to be able to accommodate for instances where there is no "selected", and the regular expression will simply not match, instead of matching something way down further from another select list.

Thanks for your help!
Avatar of kaufmed
kaufmed
Flag of United States of America image

But I do need to be able to accommodate for instances where there is no "selected", and the regular expression will simply not match

Can you clarify this? If it is going down to the next match, then it is not matching the first one!
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Note that I've changed a key part of the pattern where there was:
.*?
to:
(?:(?!</select>).)*?
which should prevent the match looking forward to a select further down the page.
Avatar of aaron900
aaron900

ASKER

This is perfect! Thanks for the quick and accurate response! These lookarounds definitely take some getting used to!