我正在使用 Node js 制作一个基本的聊天应用程序,并且正在尝试向聊天添加命令。
示例:用户可以使用此命令添加好友 /add name
t = "/add Smith"
var c = t.match(/^\s*([/](?:\S+\d+|add|send))\s+\S+/i);
console.log(c[0])
// '/add Smith'
但我听不到第三个词:
t = "/send Smith 5000"
var c = t.match(/^\s*([/](?:\S+\d+|add|send))\s+\S+/i);
console.log(c)
// '/send Smith'
//third variable is missing
它仍然给出 c[0]
中的前两个单词,但我也需要第三个单词。我该如何解决这个问题?
最佳答案
\S+
将匹配 1 个或多个非空格,因此一旦在 Smith
后面找到空格就会停止。使用 .+
匹配 "send "
之后的所有内容。
var c = t.match(/^\s*([/](?:\S+\d+|add|send))\s+.+/i);
//=> ["/send Smith 5000", "/send"]
关于javascript - 正则表达式检查句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27363331/