2014-01-25 26 views
1

以下代碼的行爲並不像預期的那樣 - 正則表達式匹配運行,並且我收到我期望的消息,如果匹配。但是,如果'msg'包含我正在尋找的其他文本內容,例如'searchstring2'(並且我通過日誌記錄驗證過它),那麼首先運行正則表達式匹配似乎會阻止後續條件傳遞。匹配操作有可能改變'obj'JavaScript對象的正則表達式操作會改變其內容嗎?

如果我將正則表達式匹配移動到if/else隊列的末尾,則其他條件按預期工作。

spooky.on('remote.message', function(msg) { 
    this.echo('======================'); 
    this.echo(msg); 
    var obj = JSON.parse(msg); 
    this.echo(obj.type); 
    this.echo('remote message caught: ' + obj.match_state.toString()); 

    //this.echo(obj.stroke); 
    regex = /(string_)(looking|whatever)([\d])/g; 
    if(obj.stroke.match(regex)) { 
     this.echo('physio message' + obj.stroke.match(regex)[0]); 
     TWClient.messages.create({ 
     body:obj.stroke.match(regex)[0]+' match id: '+obj.matchid, 
     ... 
     }, function(err, message) { 
      //error handling 
     }); 
    } 

    else if (obj.type.toString() == "searchstring2" && obj.match_state.toString() == "C") { 
     this.echo(obj.type); 
     TWClient.messages.create({ 
      body:obj.surname1 +' v '+obj.surname2+ ' started time: '+obj.utc_timestamp, 
      ... 
      if(err) { 
       console.log(err, message); 
      } 
     }); 
    } 

    else if (obj.type.toString() == "searchstring3" && obj.match_state.toString() =="F") { 
     this.echo(obj.match_state); 
     TWClient.messages.create({ 
      body:'match '+obj.matchid+' finished, time: '+obj.utc_timestamp, 
     ... 

     }, function(err, message) { 
      //error handling 
     }); 
    } 




}); 
+0

你忘了'var'你的正則表達式變量 – Tomalak

回答

0

使用g標誌構建的正則表達式是一種迭代器:操作會更改其內部狀態。

您可能不需要此標誌。

你也可以重寫你的代碼是這樣的:

var regex = /(string_)(looking|whatever)([\d])/g, // don't forget the var 
    m = obj.stroke.match(regex); 
if (m) { 
    this.echo('physio message' + m[0]); 
    TWClient.messages.create({ 
    body:m[0]+' match id: '+obj.matchid, 

這將避免出現兩個無用match操作。

+0

'if(m = obj.stroke.match(regex)){'我猜你的意思是'm =='並且任務應該在 – Deryck

+0

之前@Deryck否,我的意思是我寫的東西。但在這種情況下,if(assignement)形式確實沒有收益。 –

+0

@dystroy就這樣我很清楚,你是說如果我使用/ g進行全局匹配,那麼obj的內部狀態會改變? – codecowboy