以下代码的行为不符合预期 - 正则表达式匹配运行,如果存在匹配,我会收到预期的消息。但是,如果 '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,
这将避免两个无用的匹配
操作。
关于javascript - javascript 对象上的正则表达式操作会改变其内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21348815/