匹配多个值

时间:2011-10-11 08:11:37

标签: javascript regex

我有一个这样的字符串:

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

和正则表达式匹配:

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

它工作(有点'),但尽管如此,我正在使用捕获组来获取(composer_session_id|is_explicit_place)([_a-zA-Z0-9]+)结果数组只包含两个元素(匹配字符串中最大的): / p>

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

我在这里缺少什么?

如何在一次运行中使用regexp获取字符串:composer_session_id,is_explicit_place,1557423901和u436754_5?

奖励要点解释为什么只返回两个字符串以及获取我需要的值的解决方案不涉及使用split()和/或replace()

1 个答案:

答案 0 :(得分:0)

如果正则表达式与g标志一起使用,则方法string.match仅返回匹配的数组,但不包括捕获的组。方法RegExp.exec返回最后一次匹配的数组和最后一次匹配中捕获的组,这也不是解决方案。 为了以相对简单的方式实现您的需求,我建议您研究一下替换器功能:

<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>