我可以写正则表达式和使用.test()像这样在javascript?



好的,我是javascript的新手,有一个关于在其中使用正则表达式的问题。

我可以编写正则表达式并使用.test()这样的一个基于消息的不和谐机器人的响应来测试和给出这样的消息回复基于它是否匹配:

let myRegex = /morning/i;
if (myRegex.test(msg.content)) {
msg.reply("Good Morning!");
}
myRegex = /some text/i;
if (myRegex.test(msg.content)) { 
msg.reply("Bot replies to some text");
}
myRegex = /some other text/i;
if (myRegex.test(msg.content)) { 
msg.reply("bot replies to some other text");
}

它似乎工作,但在执行它。但由于某种原因,感觉这是错误的做事方式,因为我每次都在.test()之前指定myRegex。


在此之前,我最初是这样使用if语句的,但问题是,当有更多的单词时,我必须编写一个单独的消息,因为它只会检查确切的消息:

if (msg.content.toLowerCase() === 'morning') {
msg.reply('https://media.giphy.com/media/34dapC0zP8iSQ0wjHX/giphy.gif ');
}

我注意到第二个代码只适用于消息输入,如'morning'或'morning'或'morning',但不适用于'good morning'或'good morning' 'good morning'等。

所以,我正在考虑移动到正则表达式,但我想确保我做的是正确的。

有人能帮我一下吗?

你做的很好。唯一潜在的小问题(只是风格上的)是你不必要地重新分配一个变量。

如果您认为提前声明模式并将其放入变量中看起来很奇怪,您可以自由地将其内联化(并且您可能希望使用else if,以便在匹配多个测试的情况下不会对同一消息进行多个回复)

} else if (/some text/i.test(msg.content)) { 
msg.reply("Bot replies to some text");
} else if (/some other text/i.test(msg.content)) { 
msg.reply("bot replies to some other text");
}

您可以使用includes方法检查字符串是否包含另一个字符串作为子字符串:

if (msg.content.toLowerCase().includes('morning')) {
// ...
}

要回答这个问题,是否应该每次都重新定义RegEx变量?简短的回答——No.

虽然这个特定的例子没有任何明显的缺点,但是像这样重新定义变量可能会导致未知内容的bug。

我将内联正则表达式,不过您也可以为每次检查创建一个新变量。下面是一个内联正则表达式的例子:

if (/morning/i.test(msg.content)) {
msg.reply("Good Morning!");
}
if (/some text/i.test(msg.content)) {
msg.reply("Bot replies to some text");
}
if (/some other text/i.test(msg.content)) {
msg.reply("Bot replies to some other text");
}

如果你愿意,你可以把正则表达式用括号括起来。

if ((/morning/i).test(msg.content)) { /* ... */ }

相关内容

最新更新