JavaScript对象上的正则表达式操作会更改其内容



以下代码的行为不如预期-Regex Match运行,如果有匹配,我会收到我期望的消息。但是,如果'msg'包含我正在寻找的其他文本内容,例如'searchstring2'(并且我已经通过记录验证了它的验证),则首先运行REGEX匹配项似乎可以防止后续条件通过。匹配操作是否有可能更改'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操作。

最新更新