2011-10-11 117 views
-1

我有一个像这样的字符串:匹配多个值

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]+)结果数组只包含两个元素(最大匹配字符串):

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

我在这里错过了什么?

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

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

+0

你知道你可以嵌套捕获组? –

+0

是的,我知道 - 这对我有帮助吗? – WTK

+0

你可以给未经转义的原始字符串和正则表达式吗? – pastacool

回答

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

正如一个侧面说明 - 它不是真的,String.match()只返回匹配数组并忽略捕获组。看看这里的例子:http://jsfiddle.net/Z7gN3/2/。没有“g”标志的正则表达式包含捕获组(唯一的问题是 - 它的第一个匹配,因为没有全局标志:)) – WTK

+0

@WTK,是的,你说得对,我错误地认为string.match方法。 – Alexey

+0

@WTK更新:string.match与g确实返回没有捕获组的匹配数组,这就解释了为什么你会得到你在问题中指定的数组,而不是g--你是如何说的。 – Alexey