簡體   English   中英

對javascript對象進行的正則表達式運算會改變其內容嗎?

[英]Would a regular expression operation on a javascript object alter its contents?

以下代碼無法正常運行-正則表達式匹配運行,如果匹配,我會收到我期望的消息。 但是,如果'msg'包含我正在尋找的其他文本內容,例如“ searchstring2”(並且我已經通過日志記錄進行了驗證),那么首先運行正則表達式匹配似乎可以防止后續條件通過。 匹配操作是否有可能改變'obj'

如果我將正則表達式匹配項移至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
        });
    }




});

使用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操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM