为变量添加正则表达式



我正试图使一个irc bot像这样输入user: +1,我想有一个最终结果,我可以有一个主号码被添加到,从#某人键入+#。

期望输出:#x added: 1 rep: 1 executed[+]second execution#x added: 1 rep: 2 executed[+]

实际输出#x added: +1 rep: +1undefined executed[+]秒相同。

我试过使用Number(commandName),随着toString().replace(/Ds/g,'')我得到了一些有希望的结果,但他们似乎有一些问题,所以我取消了代码…

那么总结一下,我怎样才能把这些数字加在一起而不加+呢?

const tmi = require('tmi.js');
// Define configuration options
const opts = {
identity: {
username: "x",
password: "x"
},
channels: [
"#x"
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
// Connect to Twitch:
client.connect();
const totalnum = 0;
// Called every time a message comes in
function onMessageHandler(target, context, msg, self) {
if (self) {
return;
} // Ignore messages from the bot
// Remove whitespace from chat message
let commandName = msg.trim();
var regexadd = /([+]d*)[^+s]/;
// If the command is known, let's execute it
if (regexadd.exec(commandName)) {
var totalnum = addem(commandName, totalnum);
console.log(target, `added:`, commandName, `rep:`, totalnum, `executed[+]`)
} else {
console.log(`* Unknown command ${commandName}`);
}
function addem(x, y) {
return (x + y);
}

}

// Called every time the bot connects to Twitch chat
function onConnectedHandler(addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}

我发现你的代码有一些问题:

  • 您没有添加数字。addem()的第一个参数是命令的名称,它应该是在regex捕获组中捕获的数字。
  • 您的regex包含捕获组中的+符号,您可能想要排除它
  • 你应该用ParseInt()或隐式地用+解析exec的结果为提示
  • 使用RegExp.prototype.exec()代替RegExp.prototype.match()来检索捕获组

可以是这样的

var regexadd = /+(d*)[^+s]/;    
if (regexadd.exec(commandName)) {
var totalnum = addem(+commandName.match(regexadd)[1], totalnum);
console.log(target, `added:`, commandName, `rep:`, totalnum, `executed[+]`)
}

我也认为if语句最好使用RegExp.prototype.test()而不是RegExp.prototype.exec()-您将限制结果为真或假。

最新更新