2011-10-11 122 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