开发者

Matching for multiple values

I got a string like this:

str = 'autocomplete=\\\"off\\\" name=\\\"composer_session_id\\\" value=\\\"1557423901\\\" \\\/>\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"is_explicit_place\\\" id=\\\"u436754_5\\\"';

and a regexp match:

str.match(/(composer_session_id|is_explicit_place)\\" (?:value|id)=\\"([_a-zA-Z0-9]+)\\"/g)

It working (kinda'), but despite the fact, I'm using capture groups to get 开发者_Python百科the (composer_session_id|is_explicit_place) and ([_a-zA-Z0-9]+) the result array contains only two elements (biggest of matched strings):

["composer_session_id\" value=\"1557423901\"", "is_explicit_place\" id=\"u436754_5\""]

What am I missing here?

How can I use regexp to get strings: composer_session_id, is_explicit_place, 1557423901 and u436754_5 in a single run?

Bonus points for explanation why there are only two strings returned and solution for getting values I need that doesn't involve using split() and/or replace().


If regex is used with g flag, method string.match returns array only of matches, it doesn't include captured groups. Method RegExp.exec returns array with the last match and captured groups in the last match, which is not a solution either. To achieve what you need in a comparatively simple way I suggest to look into the replacer function:

<script type="text/javascript">
    var result = []

    //match - the match
    //group1, group2 and so on - are parameters that contain captured groups
    //number of parameters "group" should be exactly as the number of captured groups
    //offset - the index of the match
    //target - the target string itself
    function replacer(match, group1, group2, offset, target)
    {
        if (group1 != "")
        {
            //here group1, group2 should contain values of captured groups
            result.push(group1);
            result.push(group2);
        }
        //if we return the match 
        //the target string will not be modified
        return match;
    }

    var str = 'autocomplete=\\\"off\\\" name=\\\"composer_session_id\\\" value=\\\"1557423901\\\" \\\/>\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"is_explicit_place\\\" id=\\\"u436754_5\\\"';
    //"g" causes the replacer function 
    //to be called for each symbol of target string
    //that is why if (group1 != "") is needed above
    var regexp = /(composer_session_id|is_explicit_place)\\" (?:value|id)=\\"([_a-zA-Z0-9]+)\\"/g;
    str.replace(regexp, replacer);
    document.write(result);
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜