Search code examples
cregexperformance-testingloadrunner

Regex for picking up a color name from HTTP response


I am using Loadrunner and need to come up with a regex that will pick up a particular word from the HTTP response coming in and save it in a parameter.

The response looks like this:

\t\t\t\t\t<option value="Rose taupe" id="WD26" class="WD26">Rose taupe</option>\n
\t\t\t\t\t<option value="Myrtle" id="WD20" class="WD20">Myrtle</option>\n
\t\t\t\t\t<option value="Deep carmine pink" id="WD142" class="WD142">Deep carmine pink</option>\n
\t\t\t\t\t<option value="Wild Strawberry" id="WD66" class="WD66">Wild Strawberry</option>\n
\t\t\t\t\t<option value="Cream" id="WD72" selected="selected" class="WD72">Cream</option>\n
\t\t\t\t\t<option value="Tangerine yellow" id="WD94" class="WD94">Tangerine yellow</option>\n

I want to pick up the color that is selected in a drop down menu in the front end, in the response this color line has selected="selected" in it. This is however random for each instance hence the regex has to pickup the color name from the line which contains selected="selected".

I then have to use it in my script as follows:

web_reg_save_param_regexp ("ParamName=SelectedColor",
"RegExp=-regular expression here-",
"Ordinal=All",
LAST);

Thank you for your help!


Solution

  • The RegExp /<\s*option\s+(?=.*selected\s*=).*value\s*=\s*(?:"([^"]*)"|'([^']*)')/g will match the option tag with the selected attribute. The order of attributes is arbitrary. If attribute quotes may be ' then you need to handle the second match group, see example.

    var s = '\t\t\t\t\t<option value="Rose taupe" id="WD26" class="WD26">Rose taupe</option>\n' +
            '\t\t\t\t\t<option value="Myrtle" id="WD20" class="WD20">Myrtle</option>\n' +
            '\t\t\t\t\t<option value="Deep carmine pink" id="WD142" class="WD142">Deep carmine pink</option>\n' +
            '\t\t\t\t\t<option value="Wild Strawberry" id="WD66" class="WD66">Wild Strawberry</option>\n' +
    
            '\t\t\t\t\t<option value="Cream" id="WD72" selected="selected" class="WD72">Cream</option>\n' +
    
            '\t\t\t\t\t<option id="WD72" value=\'Cream\' selected="selected" class="WD72">Cream</option>\n' +
    
            '\t\t\t\t\t<option value="Tangerine yellow" id="WD94" class="WD94">Tangerine yellow</option>\n';
    
    var re = /<\s*option\s+(?=.*selected\s*=).*value\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
    var m;
    
    while (m = re.exec(s)) {
        console.log("Selected color: " + (m[1]||m[2]) + ", match " + m[0]);
    }